-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
49 lines (44 loc) · 1.48 KB
/
db.js
File metadata and controls
49 lines (44 loc) · 1.48 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
import fs from 'fs';
import path from 'path';
import { Sequelize } from "sequelize";
import { logger } from './libs/logger';
let db = null;
module.exports = (app) => {
if(!db){
//database settings
const config = app.libs.config;
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
config.params,
{
logging: (sql) => {
logger.info(`[${new Date()}] - ${sql}`);
},
}
);
db = {
// first being a DB connection,
sequelize,
// second being the Sequlize library.
Sequelize,
models: {}
};
const dir = path.join(__dirname, 'models');
//returns an array of strings(file names) from directory 'models'
fs.readdirSync(dir).forEach(file => {
//iterate to import and load all models to sequelize
const modelDir = path.join(dir, file);
// const model = sequelize.import(modelDir);
const model = require(modelDir)(sequelize, Sequelize)
//then insert it to db.models that was null {}
db.models[model.name] = model;
});
//To ensure the models relationship
Object.keys(db.models).forEach(key => {
db.models[key].associate(db.models)
});
}
return db;
}