Skip to content

Instantly share code, notes, and snippets.

@evantahler
Last active December 12, 2015 04:24
Show Gist options
  • Save evantahler/d9becae3da1ea57178db to your computer and use it in GitHub Desktop.
Save evantahler/d9becae3da1ea57178db to your computer and use it in GitHub Desktop.
sequelize + actionhero + migrations
var path = require('path');
var config = require(__dirname + '/config/sequelize');
var env = 'default';
if(config[process.env.NODE_ENV]){ env = process.env.NODE_ENV; }
config = config[env].sequelize();
config.config = __filename;
config['migrations-path'] = path.resolve('db', 'sequelize', 'migrate');
module.exports = config;
  • npm install sequelize
  • npm install sequelize-cli

in package.json

  • tasks.migrate: "sequelize db:migrate"
exports.default = {
sequelize: function(api){
return {
"dialect" : "mysql",
"port" : parseInt( process.env.MYSQL_PORT ),
"database" : process.env.MYSQL_DATABASE,
"host" : process.env.MYSQL_HOST,
"username" : process.env.MYSQL_USER,
"password" : process.env.MYSQL_PASS,
"logging" : false,
"toSync" : false,
};
}
};
exports.test = {
sequelize: function(api){
return {
"dialect" : "mysql",
"database" : 'messagebot_test',
"host" : '127.0.0.1',
"username" : 'root',
"password" : null,
"logging" : false,
"toSync" : false,
};
}
};
var path = require('path');
var fs = require('fs');
var Sequelize = require('sequelize');
module.exports = {
loadPriority: 100,
startPriority: 100,
initialize: function(api, next){
api.models = api.models || {};
var sequelizeInstance = new Sequelize(
api.config.sequelize.database,
api.config.sequelize.username,
api.config.sequelize.password,
api.config.sequelize
);
api.sequelize = {
sequelize: sequelizeInstance,
connect: function(callback){
var dir = path.normalize(api.projectRoot + '/models');
fs.readdirSync(dir).forEach(function(file){
var nameParts = file.split("/");
var name = nameParts[(nameParts.length - 1)].split(".")[0];
api.models[name] = api.sequelize.sequelize.import(dir + '/' + file);
});
if(api.config.sequelize.toSync === true){
api.sequelize.sequelize.sync().then(function(){
callback();
}).catch(function(error){
callback(error);
});
}else{
callback();
}
},
test: function(callback){
api.models.user.count().then(function(data){
api.log('connected to sequelize');
callback();
}).catch(function(error){
api.log('cannot connect to sequelize:', 'crit');
api.log(error, 'crit');
callback(error);
});
},
query: function(q, type, callback){
if(typeof type === 'function'){ callback = type; type = null; }
if(!type){ type = api.sequelize.sequelize.QueryTypes.SELECT; }
api.sequelize.sequelize.query(q, {type: type}).then(function(users){
callback(null, users);
}).catch(callback);
},
};
next();
},
start: function(api, next){
api.sequelize.connect(function(error){
if(error){ return next(error); }
api.sequelize.test(next);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment