我在使用 TypeOrm 挂钩“BeforeUpdate”时遇到问题
我试图通过传递一个简单的字符串并调用 save 方法来触发 beforeUpdate 挂钩,然后对密码进行哈希处理来更新用户实体密码,但在调用 save 方法时此挂钩不起作用。
这就是我所拥有的
用户服务.ts
async update(id: number, updateUserDto: UpdateUserDto) {
const roles =
updateUserDto.roles &&
(await Promise.all(
updateUserDto.roles.map((name) => this.preloadRoleByName(name))
));
const user = await this.userRepository.findOneOrFail(id);
if (!user) {
throw new NotFoundException(`User with ID #${id} not found`);
}
const toSaveUser = {
...user,
...updateUserDto,
roles,
};
return await this.userRepository.save(toSaveUser);
}
Run Code Online (Sandbox Code Playgroud)
用户实体.ts
.
.
.
@Column()
@Exclude()
password: string;
@BeforeInsert()
@BeforeUpdate()
private async hashPassword() {
const rounds = 10;
const salt = await …Run Code Online (Sandbox Code Playgroud)