-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
93 lines (82 loc) · 1.98 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const Sequelize = require('sequelize');
const uuid = require('node-uuid');
const config = require('./config');
console.log('init sequelize');
function generateId() {
return uuid.v4();
}
const sequelize = new Sequelize(config.database, config.username, config.password ,{
host: config.host,
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 30000,
},
});
const ID_TYPE = Sequelize.STRING(50);
function defineModel(name, attributes) {
let attrs = {};
for (let key in attributes) {
const 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.createdAt = {
type: Sequelize.BIGINT,
allowNull: false
};
attrs.updatedAt = {
type: Sequelize.BIGINT,
allowNull: false
};
// console.log('model defined for table: ' + name);
return sequelize.define(name, attrs, {
tableName: name,
timestamps: false,
hooks: {
beforeValidate: function (obj) {
let now = Date.now();
if (obj.isNewRecord) {
if (!obj.id) {
obj.id = generateId();
}
obj.createdAt = now;
obj.updatedAt = now;
} else {
obj.updatedAt = Date.now();
}
}
}
});
}
const TYPES = ['STRING', 'INTEGER', 'BIGINT', 'TEXT', 'DOUBLE', 'DATEONLY', 'BOOLEAN'];
var exp = {
defineModel: defineModel,
sync: () => {
// only allow create ddl in non-production environment:
if (process.env.NODE_ENV !== 'production') {
sequelize.sync({ force: true });
return console.log('sequelize.sync');
} else {
throw new Error('Cannot sync() when NODE_ENV is set to \'production\'.');
}
}
};
for (let type of TYPES) {
exp[type] = Sequelize[type];
}
exp.ID = ID_TYPE;
exp.generateId = generateId;
module.exports = exp;