Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Last active January 2, 2018 23:02
Show Gist options
  • Save renatoargh/f79928da40864591da2f57b8941edc01 to your computer and use it in GitHub Desktop.
Save renatoargh/f79928da40864591da2f57b8941edc01 to your computer and use it in GitHub Desktop.
const path = require('path')
const fs = require('fs')
const Sequelize = require('sequelize')
const { CONNECTION_STRING } = process.env
const modelsFolder = path.join(__dirname, '../models')
const models = {}
module.exports = () => {
// 1. Initialisation code
const sequelize = new Sequelize(CONNECTION_STRING, {
dialect: 'mssql',
dialectOptions: { encrypt: true }
})
fs.readdirSync(modelsFolder).forEach(modelPath => {
modelPath = path.join(modelsFolder, modelPath)
let model = require(modelPath)
model = sequelize.import(modelPath, model)
model = model.applySchema('shared') // 2. Important line
models[model.name] = model
})
Object.values(models)
.filter(m => m.associate)
.forEach(m => m.associate(models))
return (req, res, next) => {
req.models = models
req.applySchema = schema => { // 3. Function to set the schema
Object.keys(req.models).forEach(modelName => {
const model = req.models[modelName]
req.models[modelName] = model.applySchema(schema)
})
}
next()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment