Created
March 22, 2019 07:35
-
-
Save hypeJunction/600e04c9353038d2601caabe75888151 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
import { inspect } from 'util'; | |
import Sequelize from 'sequelize'; | |
export default function DatabaseConnection (config, logger) { | |
const { | |
dialect, | |
name, | |
host, | |
port, | |
user, | |
password, | |
} = config.db; | |
const logging = (...args) => { | |
args = args.map((arg) => { | |
return inspect(arg); | |
}); | |
logger.debug(...args); | |
}; | |
return new Sequelize(name, user, password, { | |
host, | |
dialect, | |
port, | |
logging, | |
operatorsAliases: false, | |
define: { | |
underscored: true, | |
}, | |
}); | |
} |
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
import schema from '../db/schema'; | |
import BaseModel from '../db/BaseModel'; | |
export default class Database { | |
constructor (connection) { | |
// connection is an instance of DatabaseConnection | |
this.connection = connection; | |
this.loadedModels = null; | |
} | |
get models () { | |
return this.loadedModels; | |
} | |
loadModels (services) { | |
/** @type Object<Sequelize.Model> */ | |
const models = {}; | |
Object.keys(schema).forEach((modelName) => { | |
const definition = schema[modelName]; | |
definition.name = definition.name || modelName; | |
let Constructor = BaseModel; | |
if (typeof definition.class === 'function') { | |
Constructor = definition.class; | |
} | |
if (!(Constructor.prototype instanceof BaseModel)) { | |
throw new Error(`Model class for ${definition.name} must extend BaseModel`); | |
} | |
models[definition.name] = Constructor.init(definition, services); | |
}); | |
Object.keys(schema).forEach((modelName) => { | |
models[modelName].associate(); | |
models[modelName].registerHooks(); | |
// Here we also register global sequelize hooks | |
// e.g. in our application we added eagerLoader method to the BaseModel, | |
// in order to preload associations (due to the complex nature of relationships in our app, | |
// native sequelize approach of eager loader just wouldn't work) | |
models[modelName].afterFind(models[modelName].eagerLoader); | |
}); | |
this.loadedModels = models; | |
} | |
async sync (options) { | |
// @warning This should only be used by tests | |
// for development and production instances use cli | |
await this.connection.sync(options || {}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment