-
-
Save hc3/280a0777680b64cdeee207e9c0b9cde1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Sequelize = require('sequelize') | |
const fs = require('fs') | |
const path = require('path') | |
let database = null | |
const loadModels = (sequelize) => { | |
const dir = path.join(__dirname, '../modules/models') | |
const models = [] | |
fs.readdirSync(dir).forEach((file) => { | |
const modelDir = path.join(dir, file) | |
const model = sequelize.import(modelDir) | |
models[model.name] = model | |
}) | |
Object.keys(models).forEach(function (object) { | |
if ('associate' in models[object]) { | |
models[object].associate(models) | |
}; | |
}) | |
return models | |
} | |
module.exports = (app) => { | |
if (!database) { | |
const config = app.config | |
const sequelize = new Sequelize( | |
config.database, | |
config.username, | |
config.password, | |
config.params | |
) | |
database = { | |
sequelize, | |
Sequelize, | |
models: {} | |
} | |
database.models = loadModels(sequelize) | |
sequelize.sync().done(() => database) | |
} | |
return database | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment