抽象一个model
首先接着我们前一篇博客说到的,我们现在使用基础的增删改查都非常费事更别谈我们要做什么大型项目了。所以为了简化我们的代码我们有必要抽象一个model类来统筹表映射。
创建model类(对之前的model进行修改)
app_need/db.js
'use strict';
const Sequelize =
require(
'sequelize');
const config =
require(
'../app_need/config');
var mysql_config = config.mysql_config;
var sequelize =
new Sequelize(mysql_config.db_name, mysql_config.db_user, mysql_config.db_password, {
host: mysql_config.db_host,
dialect:
'mysql',
pool: {
max:
5,
min:
0,
idle:
30000
}
});
function defineModel(name, attributes) {
var attrs = {};
for (
let key
in attributes) {
let value = attributes[key];
if (
typeof value ===
'object' && value[
'type']) {
value.allowNull = value.allowNull ||
false;
attrs[key] = value;
}
else {
attrs[key] = {
type: value,
allowNull:
false
};
}
}
attrs.id = {
type: Sequelize.INTEGER(
50),
primaryKey:
true,
autoIncrement:
true
};
attrs.createdAt = {
type: Sequelize.BIGINT,
allowNull:
false
};
attrs.updatedAt = {
type: Sequelize.BIGINT,
allowNull:
false
};
attrs.version = {
type: Sequelize.BIGINT,
allowNull:
false
};
return sequelize.define(mysql_config.db_prefix + name, attrs, {
tableName: mysql_config.db_prefix_name,
timestamps:
false,
hooks: {
beforeValidate:
function (obj) {
let now =
Date.now();
if (obj.isNewRecord) {
if (!obj.id) {
obj.id = Sequelize.generateId;
}
obj.createdAt = now;
obj.updatedAt = now;
obj.version =
0;
}
else {
obj.updatedAt =
Date.now();
obj.version++;
}
}
}
});
}
module.exports = defineModel;
这个模块暴露一个方法,这个方法用来生成具体的某个表的映射,并且约定了一些基础规则,这些基础规则属性不需要在重新写入了。 然后如果要创建表映射模块的话
创建表映射模块
db_model/users.js
'use strict';
const Sequelize =
require(
'sequelize');
const definddb=
require(
'../../app_need/db');
var attr={
name:Sequelize.STRING(
30),
password:Sequelize.STRING(
50)
}
var db_users= definddb(
'users',attr);
module.exports=db_users;
之后就可以用这个暴露的obj使用Sequelize的语法创建对应的数据增删改查了。 最终项目地址:https://github.com/jijuxie/koa2_all.git
转载请注明原文地址: https://ju.6miu.com/read-36244.html