models initialization refactored, better dev experience as backend hmr is working

This commit is contained in:
lesion
2022-12-23 01:08:14 +01:00
parent 380eaa87ca
commit cbed0288fe
43 changed files with 624 additions and 707 deletions

View File

@@ -1,53 +1,49 @@
const bcrypt = require('bcryptjs')
const { Model, DataTypes } = require('sequelize')
const sequelize = require('./index').sequelize
class User extends Model {}
User.init({
settings: {
type: DataTypes.JSON,
defaultValue: []
},
email: {
type: DataTypes.STRING,
unique: { msg: 'error.email_taken' },
validate: {
notEmpty: true
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('user', {
settings: {
type: DataTypes.JSON,
defaultValue: []
},
index: true,
allowNull: false
},
description: DataTypes.TEXT,
password: DataTypes.STRING,
recover_code: DataTypes.STRING,
is_admin: DataTypes.BOOLEAN,
is_active: DataTypes.BOOLEAN
}, {
sequelize,
modelName: 'user',
scopes: {
withoutPassword: {
attributes: { exclude: ['password', 'recover_code'] }
email: {
type: DataTypes.STRING,
unique: { msg: 'error.email_taken' },
validate: {
notEmpty: true
},
index: true,
allowNull: false
},
withRecover: {
attributes: { exclude: ['password'] }
description: DataTypes.TEXT,
password: DataTypes.STRING,
recover_code: DataTypes.STRING,
is_admin: DataTypes.BOOLEAN,
is_active: DataTypes.BOOLEAN
}, {
scopes: {
withoutPassword: {
attributes: { exclude: ['password', 'recover_code'] }
},
withRecover: {
attributes: { exclude: ['password'] }
}
}
})
User.prototype.comparePassword = async function (pwd) {
if (!this.password) { return false }
return bcrypt.compare(pwd, this.password)
}
})
User.beforeSave(async (user, _options) => {
if (user.changed('password')) {
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(user.password, salt)
user.password = hash
}
})
User.prototype.comparePassword = async function (pwd) {
if (!this.password) { return false }
return bcrypt.compare(pwd, this.password)
return User
}
User.beforeSave(async (user, _options) => {
if (user.changed('password')) {
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(user.password, salt)
user.password = hash
}
})
module.exports = User