Created
October 29, 2014 17:16
-
-
Save zealoushacker/1d328ae3b081bcfa4389 to your computer and use it in GitHub Desktop.
sequelize models/index.js file drop-in replacement
This file contains hidden or 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
"use strict"; | |
var fs = require("fs"); | |
var path = require("path"); | |
var Sequelize = require("sequelize"); | |
var env = process.env.NODE_ENV || "development"; | |
var config = require(__dirname + '/../config/config.json')[env]; | |
var db = {}; | |
var sequelize; | |
var match; | |
if (process.env.DATABASE_URL) { | |
match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/) | |
sequelize = new Sequelize(match[5], match[1], match[2], { | |
dialect: 'postgres', | |
protocol: 'postgres', | |
port: match[4], | |
host: match[3], | |
logging: true //false | |
}); | |
} else { | |
sequelize = new Sequelize(config.database, config.username, config.password, config); | |
} | |
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; | |
module.exports = db; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment