-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
64 lines (53 loc) · 1.32 KB
/
db.js
File metadata and controls
64 lines (53 loc) · 1.32 KB
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
import fs from 'fs'
import path from 'path'
import Sequelize from 'sequelize'
function resolveOwn(relativePath) {
return path.resolve(__dirname, relativePath)
}
let db = null
module.exports = app => {
if (!db) {
const basename = path.basename(module.filename)
const config = app.libs.config
const logger = app.libs.logger
const sequelize = new Sequelize(
config.db.name,
config.db.username,
config.db.password,
{
...config.db.options,
define: {
underscored: true,
},
}
)
// 测试连接
sequelize.authenticate()
.then((err) => {
logger.debug('DB: Connected', err)
})
.catch((err) => {
logger.debug('DB: Not Connected', err)
})
db = {
sequelize,
Sequelize,
execute: ::sequelize.transaction,
models: {},
}
const dir = resolveOwn('./models')
fs.readdirSync(dir)
.filter(file => (file.indexOf('.') !== 0) && (file !== basename))
.forEach((file) => {
const modelDir = path.join(dir, file)
const model = sequelize.import(modelDir)
db.models[model.name] = model
})
Object.keys(db.models).forEach((key) => {
if ('associate' in db.models[key]) {
db.models[key].associate(db.models)
}
})
}
return db
}