Created
October 18, 2020 12:56
-
-
Save xgracias/95fd7e9b49dd062d5b37d6dba2ec2040 to your computer and use it in GitHub Desktop.
User model
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 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