forked from robmclarty/cred-auth-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model_builder.js
38 lines (28 loc) · 1.09 KB
/
model_builder.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
'use strict'
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const getModelFiles = dir => fs.readdirSync(dir)
.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))
.map(file => path.join(dir, file))
// Take an array of sequelize model files and load/init them with sequelize and
// return an object containing each model as an attribute.
const modelBuilder = (customDir, url, dialect) => new Promise((resolve, reject) => {
const sequelize = new Sequelize(url, { dialect, logging: false })
const models = {}
const customFiles = getModelFiles(customDir)
const coreFiles = getModelFiles('./server/models')
const files = [...customFiles, ...coreFiles]
files.forEach(file => {
const model = sequelize.import(file)
models[model.name] = model
console.log('Loaded model ', model.name)
})
Object.keys(models).forEach(modelName => {
if ('associate' in models[modelName]) models[modelName].associate(models)
})
models.sequelize = sequelize
models.Sequelize = Sequelize
resolve(models)
})
module.exports = modelBuilder