Created
August 6, 2018 14:01
-
-
Save AlekseyA/281418fca139e235ddf1cbba8f44f234 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
| /* eslint-disable no-param-reassign */ | |
| const { hashPassword } = require('../auth/helpers'); | |
| module.exports = (sequelize, DataTypes) => { | |
| const User = sequelize.define('user', { | |
| email: { | |
| type: DataTypes.STRING, | |
| validate: { | |
| isEmail: { | |
| msg: 'Email isn\'t correct' | |
| } | |
| }, | |
| unique: 'unique_user' | |
| }, | |
| name: DataTypes.STRING, | |
| avatar: DataTypes.STRING, | |
| prename: DataTypes.STRING, | |
| role: { | |
| type: DataTypes.STRING, | |
| defaultValue: 'user' | |
| }, | |
| password: DataTypes.STRING, | |
| permissions: DataTypes.ARRAY(DataTypes.STRING), | |
| }, { | |
| underscored: true, | |
| getterMethods: { | |
| username() { | |
| if (this.role === 'user') { | |
| return `${this.prename ? this.prename : ''} ${this.name}`.trim(); | |
| } | |
| return this.name; | |
| } | |
| }, | |
| }); | |
| // eslint-disable-next-line consistent-return | |
| User.beforeValidate((user, options) => { | |
| if (!user.isNewRecord) { | |
| return undefined; | |
| } | |
| if (!options.defaults || !options.defaults.token) { | |
| if (user.email && !user.password) { | |
| throw new Error('Password is required'); | |
| } | |
| if (!user.name) { | |
| throw new Error('Name is required'); | |
| } | |
| } | |
| }); | |
| User.beforeCreate((user) => { | |
| if (user.isNewRecord && user.password) { | |
| user.password = hashPassword(user.password); | |
| } | |
| return new Promise((resolve) => { | |
| sequelize.models.role.findOne({ where: { name: user.role } }) | |
| .then((role) => { | |
| if (role) { | |
| user.permissions = role.access_list; | |
| } | |
| return resolve(user); | |
| }); | |
| }); | |
| }); | |
| User.associate = (models) => { | |
| models.user.belongsToMany(models.product, { | |
| through: { | |
| model: models.subscribe_product, | |
| unique: true | |
| }, | |
| foreignKey: 'user_id', | |
| }); | |
| }; | |
| return User; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment