【发布时间】:2020-03-24 19:58:31
【问题描述】:
我正在为我的无服务器 lambda 函数使用 Sequelize Typescript 模块。用户模型有两个钩子,beforecreate 和 beforeupdate。用户模型如下所示:
import { Table, Column, ForeignKey, BeforeCreate, BeforeUpdate, BelongsTo } from 'sequelize-typescript';
import { Role } from './role';
import bcrypt from 'bcrypt-nodejs';
import { BaseModel } from './base';
const saltRounds = 10;
@Table({
tableName: 'users'
})
export class User extends BaseModel {
@Column
firstName!: string;
@Column
lastName!: string;
@Column
password!: string;
@Column
email!: string;
@Column
isActive!: boolean;
@Column
companyId: string
@ForeignKey(() => Role)
@Column
roleId!: string;
@BelongsTo(() => Role)
role!: Role;
@BeforeCreate
@BeforeUpdate
static hashPassword(user: User) {
if (user.password) {
var salt = bcrypt.genSaltSync(saltRounds);
user.password = bcrypt.hashSync(user.password, salt);
}
}
}
现在,当我创建一个新用户时,模型会对密码进行哈希处理并将哈希密码保存在表中,但是当我尝试更新用户的密码时,密码会以纯文本形式保存。所以我猜@BeforeCreate 有效,而@BeforeUpdate 钩子没有。
我什至尝试将两个钩子分开并赋予它们自己的功能:
@BeforeCreate
static hashPasswordBeforeCreate(user: User) {
if (user.password) {
var salt = bcrypt.genSaltSync(saltRounds);
user.password = bcrypt.hashSync(user.password, salt);
}
}
@BeforeUpdate
static hashPasswordBeforeUpdate(user: User) {
if (user.password) {
var salt = bcrypt.genSaltSync(saltRounds);
user.password = bcrypt.hashSync(user.password, salt);
}
}
但是之前的更新还是不行。我做错了什么?
【问题讨论】:
标签: sequelize.js sequelize-typescript