Skip to content

Instantly share code, notes, and snippets.

@bullishgopher
Created October 18, 2020 12:56
Show Gist options
  • Save bullishgopher/95fd7e9b49dd062d5b37d6dba2ec2040 to your computer and use it in GitHub Desktop.
Save bullishgopher/95fd7e9b49dd062d5b37d6dba2ec2040 to your computer and use it in GitHub Desktop.
User model
'use strict';
var bcrypt = require('bcrypt-nodejs');
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
User.hasMany(models.Account, {
foreignKey: 'userId',
as: 'accounts'
});
User.hasMany(models.Task, {
foreignKey: 'userId',
as: 'tasks'
});
}
};
User.init({
name: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
birthday: DataTypes.DATE
}, {
sequelize,
modelName: 'User',
});
User.beforeSave((user, options) => {
if (user.changed('password')) {
user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
}
});
User.prototype.comparePassword = function (passw, cb) {
bcrypt.compare(passw, this.password, function (err, isMatch) {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
return User;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment