1 Star 0 Fork 0

zmj / nodejs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
db.js 2.19 KB
一键复制 编辑 原始数据 按行查看 历史
root 提交于 2018-02-28 19:06 . 18-2-28
const Sequelize=require('sequelize');
const uuid=require('node-uuid');
const config=require('./config');
console.log('init sequelize...');
function generateId(){
return uuid.v4();
};
var sequelize=new Sequelize(config.database,config.username,config.password,{
host:config.host,
dialect:config.dialect,
pool:{
max:5,
min:0,
idle:10000
}
});
const ID_TYPE=Sequelize.STRING(50);
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:ID_TYPE,
primaryKey:true
};
attrs.createAt={
type:Sequelize.BIGINT,
allowNull:false
};
attrs.updateAt={
type:Sequelize.BIGINT,
allowNull:false
};
attrs.version={
type:Sequelize.BIGINT,
allowNull:false
};
return sequelize.define(name,attrs,{
tableName:name,
timestamps:false,
hooks:{
beforeValidate:obj=>{
let now=Date.now();
if(obj.isNewRecord){
if(!obj.id){
obj.id=generateId();
}
obj.createAt=now;
obj.updateAt=now;
obj.version=0;
}else{
obj.updateAt=Date.now();
obj.version++;
}
}
}
});
}
var exp={
defineModel:defineModel,
sync:()=>{
if(process.env.NODE_ENV!=='production'){
sequelize.sync({force:true});
}else{
throw new Error('Cannot sync() when NODE_ENV is set to \'production\'')
}
}
};
const TYPES=['STRING','INTEGER','BIGINT','TEXT','DOUBLE','DATEONLY','BOOLEAN'];
for(let type of TYPES){
exp[type]=Sequelize[type];
};
exp.ID=ID_TYPE;
exp.generateId=generateId;
module.exports=exp;
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/zhiyuanzmj/nodejs.git
git@gitee.com:zhiyuanzmj/nodejs.git
zhiyuanzmj
nodejs
nodejs
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891