Skip to content

Instantly share code, notes, and snippets.

@hypeJunction
Created March 22, 2019 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hypeJunction/600e04c9353038d2601caabe75888151 to your computer and use it in GitHub Desktop.
Save hypeJunction/600e04c9353038d2601caabe75888151 to your computer and use it in GitHub Desktop.
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,
},
});
}
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