Skip to content

Instantly share code, notes, and snippets.

@rttomlinson
Last active April 19, 2017 23:42
Show Gist options
  • Select an option

  • Save rttomlinson/87b95ba5c8bb09799785bad160f6b1d7 to your computer and use it in GitHub Desktop.

Select an option

Save rttomlinson/87b95ba5c8bb09799785bad160f6b1d7 to your computer and use it in GitHub Desktop.
Sequelize
var path = require('path');
// Set options
var config = {
"config": "./config/sequelize.json",
"migrations-path": "./migrations/sequelize",
"seeders-path": "./seeds/sequelize",
"models-path": "./models/sequelize"
};
// Resolve paths to absolute paths
Object.keys(config).forEach((key) => {
config[key] = path.resolve(config[key]);
});
// Export like any normal module
module.exports = config;
// migrations/20170101123456-create-user.js
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
fname: {
type: Sequelize.STRING
},
lname: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.fn('NOW')
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.fn('NOW')
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
'use strict';
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
fname: {
type: DataTypes.STRING,
// First name validation
validate: {
notEmpty: {
msg: 'First name cannot be empty'
},
isAlpha: {
msg: 'First name must only be alphabetic'
}
}
},
// Last name validation
lname: {
type: DataTypes.STRING,
validate: {
notEmpty: {
msg: 'Last name cannot be empty'
},
isAlpha: {
msg: 'Last name must only be alphabetic'
}
}
},
// Email validation
email: {
type: DataTypes.STRING,
validate: {
notEmpty: {
msg: 'Email cannot be empty'
},
isEmail: {
msg: 'Email is invalid'
}
}
},
profileId: DataTypes.INTEGER
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
User.hasOne(models.Profile, {
foreignKey: "userId"
});
Skill.belongsTo(models.User, {
foreignKey: "userId"
});
Event.hasMany(models.Invitation, {
foreignKey: "eventId"
});
Event.belongsToMany(models.User, {
through: models.Invitation,
as: 'Invitee',
foreignKey: 'eventId'
});
},
// Set Model methods of custom names
// Method to pluck attributes
// out of the table
pluck: function(attributes) {
attributes = Array.isArray(attributes) ?
attributes : [attributes];
return this.findAll({
attributes
});
}
},
// Set instance methods
instanceMethods: {
name: function() {
return `${ this.fname } ${ this.lname }`;
}
}
});
return User;
};
'use strict';
let db = require('../models');
let faker = require('faker');
function _randomMarital() {
const random = Math.floor(Math.random() * 3);
const marital = ['single', 'dating', 'married'];
return marital[random];
}
function _randomGender() {
const random = Math.floor(Math.random() * 3);
const gender = ['male', 'female', 'pterodactyl'];
return gender[random];
}
let defaultMaleImagePath = '/viking_guy.jpg';
let defaultFemaleImagePath = '/viking_girl.jpg';
let defaultPtImagePath = 'https://us.123rf.com/450wm/carbouval/carbouval1511/carbouval151100004/48517216-isolated-illustration-of-a-intelligent-pterodactyl-reading-a-book.jpg';
let images = {};
images.male = defaultMaleImagePath;
images.female = defaultFemaleImagePath;
images.pterodactyl = defaultPtImagePath;
module.exports = {
up: function(queryInterface, Sequelize) {
let profiles = []
for (let i = 0; i < 50; i++) {
let gender = _randomGender()
let image = images[gender];
profiles.push({
userId: i + 1,
age: Math.floor(13 + Math.random() * 107),
location: faker.address.city(),
villagesCaptured: Math.floor(Math.random() * 10),
occupation: faker.name.jobTitle(),
marital: _randomMarital(),
gender: gender,
image: image
});
}
return queryInterface.bulkInsert('Profiles', profiles);
},
down: function(queryInterface, Sequelize) {
return queryInterface.bulkDelete('Profiles', null, {}, db.Profile);
}
};
//Modules for file system
sequelize: npm install --save sequelize
pg: npm install --save pg
pg-hstore: npm install --save pg-hstore
sequelize-cli: npm install -g sequelize-cli
//Also locally
sequelize-cli: npm install --save sequelize-cli
createdb <database name>
////Sequelize CLI - Common commands////
sequelize db:migrate
//Creating Models//
sequelize model:create --name <Model> --attributes "{column}:{datatype} {column}:{datatype}"
sequelize seed:create --name <models>
sequelize db:seed:all
sequelize db:seed:undo:all
sequelize db:migrate:undo:all && sequelize db:migrate && sequelize db:seed:all
//Default values//
createdAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.fn('NOW')
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.fn('NOW')
}
//Bottom of seeds file//
return queryInterface.bulkDelete('<Models>', null, {}, models.<Model>);
{
"development": {
"username": "your_username",
"password": null,
"database": "demo_exploring_sequelize_development",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"username": "your_username",
"password": null,
"database": "demo_exploring_sequelize_test",
"host": "127.0.0.1",
"dialect": "postgres"
},
"production": {
"use_env_variable": "DATABASE_URL",
"dialect": "postgres"
}
}
// Require the REPL module
// and models
var repl = require('repl').start({});
var models = require('./models');
// Make the `models` object
// a global variable in the
// REPL
repl.context.models = models;
// Make each model a global
// object in the REPL
Object.keys(models).forEach((modelName) => {
repl.context[modelName] = models[modelName];
});
// Provide a convenience function `lg`
// to pass to `then()` and `catch()`
// to output less verbose values for
// sequelize model query results
repl.context.lg = (data) => {
if (Array.isArray(data)) {
if (data.length && data[0].dataValues) {
data = data.map(item => item.dataValues);
}
} else {
if (data.dataValues) {
data = data.dataValues;
}
}
console.log(data);
};
const User = require('./models).User;
router.post('/job_applications', (req, res, next) => {
// Filter params
var userParams = {
fname: req.body.user.fname,
lname: req.body.user.lname,
email: req.body.user.email
};
// ...
// Begin transaction
sequelize.transaction((t) => {
// Don't create a user if
// already exists
return User.findOrCreate({
defaults: userParams,
where: { email: userParams.email },
transaction: t
})
// Executing other queries...
.catch((e) => {
// Display validation errors if we
// have them
if (e.errors) {
e.errors.forEach((err) => req.flash('error', err.message));
res.render('job_applications/new');
} else {
res.status(500);
next(e.stack)
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment