1
votes

I'm having problems using TypeOrm hook "BeforeUpdate"

I'm trying to update the user entity password, by passing a simple string and calling the save method to trigger the beforeUpdate hook and then hash the password, but this hook is not working while calling the save method.

This is what i have

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);
}

What i'm doing wrong?

BeforeInsert hook works or if i call userRepository.preload() method to update it works but it doesn't replace the roles relationship, that's why i take this approach.

Any ideas?

1

1 Answers

0
votes

Two inputs from my side,

  1. Separate function for encrypting updated password -
  @BeforeUpdate()
  async hashPasswordBeforeUpdate() {
    this.password = await bcrypt.hash(this.password, 10);
  }
  1. Try creating PUT request instead of a PATCH request

I am able to generate a valid update query, sharing just for reference-

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]