-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
76 lines (72 loc) · 1.99 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const Sequelize = require('sequelize');
const config=require('./config');
let sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: config.dialect,
pool: {
max: 5,
min: 0,
idle: 10000
}
})
let 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.BIGINT,
autoIncrement: true,
primaryKey: 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(name, attrs, {
tableName: name,
timestamps: false,
hooks: {
beforeValidate: function (obj) {
let now = Date.now();
if(obj.isNewRecord){
obj.createdAt = now;
obj.updatedAt = now;
obj.version = 0;
}
},
beforeUpdate:(obj)=>{
//更新操作 将版本++和更新时间
if (!obj.isNewRecord) {
obj.updatedAt = Date.now();
obj.version++;
}
}
}
});
}
const TYPES = ['STRING', 'INTEGER', 'BIGINT', 'TEXT', 'DOUBLE', 'DATEONLY', 'BOOLEAN', 'ENUM'];
var exp = {
defineModel: defineModel
};
for (let type of TYPES) {
exp[type] = Sequelize[type];
}
module.exports = exp;