Skip to content

Instantly share code, notes, and snippets.

@sdepold
Last active August 29, 2015 14:13
Show Gist options
  • Save sdepold/d0ddd00d090a271259a6 to your computer and use it in GitHub Desktop.
Save sdepold/d0ddd00d090a271259a6 to your computer and use it in GitHub Desktop.
Multi instance setup for sequelize
var dbAdmin = require('./db/admin.js');
var dbNormal = require('./db/normal.js');
var dbSomethingElse = require('./db/something-else.js');
var configForAdmin = { database: 'localhost', username: 'admin-user', password: 'admin-password' };
// This config could also be read from a config file!
module.exports = require('../models/index')(configForAdmin);
var configForNormalUser = { database: 'localhost', username: 'normal-user', password: 'normal-password' };
// This config could also be read from a config file!
module.exports = require('../models/index')(configForNormalUser);
var configForSomethingElse = { database: 'localhost', username: 'some-other-user', password: 'some-other-password' };
// This config could also be read from a config file!
module.exports = require('../models/index')(configForSomethingElse);
"use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
module.exports = function(config) {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize["import"](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
return db;
};
"use strict";
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
username: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Task)
}
}
});
return User;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment