TypeORM / NestJS - @BeforeUpdate 钩子不起作用

问题描述

我在使用 TypeOrm 钩子“BeforeUpdate”时遇到问题

我正在尝试通过传递一个简单的字符串并调用 save 方法来触发 beforeUpdate 钩子然后散列密码来更新用户实体密码,但是在调用 save 方法时此钩子不起作用。

这就是我所拥有的

user.service.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);
  }

user.entity.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);
}

user.controller.ts

@Patch(":id")
@UseInterceptors(ClassSerializerInterceptor)
async update(@Param("id") id: string,@Body() updateUserDto: UpdateUserDto) {
 return await this.useRSService.update(+id,updateUserDto);
}

我做错了什么?

BeforeInsert 钩子有效,或者如果我调用 userRepository.preload() 方法来更新它,但它不会替换角色关系,这就是我采用这种方法的原因。

有什么想法吗?

解决方法

我这边的两个输入,

  1. 用于加密更新密码的单独函数-
  @BeforeUpdate()
  async hashPasswordBeforeUpdate() {
    this.password = await bcrypt.hash(this.password,10);
  }
  1. 尝试创建 PUT 请求而不是 PATCH 请求

我能够生成有效的更新查询,分享仅供参考-

query: UPDATE `users` SET `levelId` = ?,`updatedAt` = ?,`password` = ? WHERE `id` IN (?) -- PARAMETERS: [null,"2021-05-07T07:27:47.198Z","$2b$10$uQOMNv57BZLB/W/9SWPbke6/OMdIDWxv3i25A8rUhA0/vEMloWb2W",1]