-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
50 lines (44 loc) · 1.55 KB
/
app.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
/* eslint no-param-reassign:0 */
const sequelize = require('sequelize');
const modelLoader = require('./lib/model_loader');
module.exports = (app) => {
app.on('configDidLoad', () => {
let dbConfigs = app.config.mysql;
// 如果dbConfigs不是陣列,一樣把它轉換成長度為1的陣列
if (!Array.isArray(dbConfigs)) dbConfigs = [dbConfigs];
app.mysql = [];
// 將sequelize放置到app/ctx裡,以供後續開發者使用
app.sequelize = sequelize;
app.context.sequelize = sequelize;
dbConfigs.forEach((itm, index) => {
const conn = new sequelize.Sequelize(itm.options);
if (dbConfigs.length === 1) {
app.mysql = conn;
} else {
app.mysql[index] = conn;
}
// 進行連線測試
conn.authenticate()
.then(() => {
console.log('\x1b[32m%s\x1b[0m', `[mysql] connection-${index} connected.`);
})
.catch((error) => {
console.error('\x1b[34m%s\x1b[0m', `[mysql] connection-${index} connect error`, error);
});
// 讀取該設定歸屬的model
if (itm.modelDir) modelLoader({ conn, modelPath: itm.modelDir });
});
// 擴充context,讓ctx也可以直接存取mysql
app.context.mysql = app.mysql;
});
app.on('beforeClose', async () => {
// 切斷所有DB連線
// 判斷app.mysql是否為單一連線,否的話就一一切斷
if (!Array.isArray(app.mysql)) {
await app.mysql.close();
} else {
const conns = app.mysql.map((v) => v.close());
await Promise.all(conns);
}
});
};