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?