Skip to content

Instantly share code, notes, and snippets.

@Harshakvarma
Last active February 4, 2018 20:53
Show Gist options
  • Save Harshakvarma/748ad24a7239b6cdaf500f24a72cc367 to your computer and use it in GitHub Desktop.
Save Harshakvarma/748ad24a7239b6cdaf500f24a72cc367 to your computer and use it in GitHub Desktop.
Sequelize example
"use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var env = process.env.NODE_ENV || "development";
var config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
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;
module.exports = db;
///https://stackoverflow.com/questions/24420800/how-to-deal-with-calling-sequelize-sync-first
// var sq = new Sequelize(dbname, user, password, config);
// db = {
// Sequelize: Sequelize,
// sequelize: sq,
// page: sq.import(__dirname + '/page.js'),
// user: sq.import(__dirname + '/user.js')
// }
// module.exports = db;
module.exports = function(sequelize, Sequelize) {
var User = sequelize.define('user', {
id: { autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER},
firstname: { type: Sequelize.STRING,notEmpty: true},
lastname: { type: Sequelize.STRING,notEmpty: true},
username: {type:Sequelize.TEXT},
about : {type:Sequelize.TEXT},
email: { type:Sequelize.STRING, validate: {isEmail:true} },
password : {type: Sequelize.STRING,allowNull: false },
last_login: {type: Sequelize.DATE},
status: {type: Sequelize.ENUM('active','inactive'),defaultValue:'active' }
});
return User;
}
User.findOne({ where : { email: email}}).then(function (user) {
if (!user) {
return done(null, false, { message: 'Email does not exist' });
}
if (!isValidPassword(user.password,password)) {
return done(null, false, { message: 'Incorrect password.' });
}
var userinfo = user.get();
return done(null,userinfo);
}).catch(function(err){
console.log("Error:",err);
return done(null, false, { message: 'Something went wrong with your Signin' });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment