Created
November 10, 2017 12:34
-
-
Save higordiego/fc7c2d57663d817d70e00e831ad0ce2d 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