我在使用 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);
}
用户实体.ts
.
.
.
@Column()
@Exclude()
password: string;
@BeforeInsert()
@BeforeUpdate()
private async hashPassword() {
const rounds = 10;
const salt = await bcrypt.genSalt(rounds);
this.password = await bcrypt.hash(this.password, salt);
}
用户控制器.ts
@Patch(":id")
@UseInterceptors(ClassSerializerInterceptor)
async update(@Param("id") id: string, @Body() updateUserDto: UpdateUserDto) {
return await this.usersService.update(+id, updateUserDto);
}
我做错了什么?
BeforeInsert 钩子有效,或者如果我调用 userRepository.preload() 方法来更新它,但它不会取代角色关系,这就是我采用这种方法的原因。
有任何想法吗?