I am using Sequelize Typescript module for my serverless lambda function. The user model has two hooks, beforecreate and beforeupdate. The user model looks like this:
import { Table, Column, ForeignKey, BeforeCreate, BeforeUpdate, BelongsTo } from 'sequelize-typescript';
import { Role } from './role';
import bcrypt from 'bcrypt-nodejs';
import { BaseModel } from './base';
const saltRounds = 10;
@Table({
    tableName: 'users'
})
export class User extends BaseModel {
    @Column
    firstName!: string;
    @Column
    lastName!: string;
    @Column
    password!: string;
    @Column
    email!: string;
    @Column
    isActive!: boolean;
    @Column
    companyId: string
    @ForeignKey(() => Role)
    @Column
    roleId!: string;
    @BelongsTo(() => Role)
    role!: Role;
    @BeforeCreate
    @BeforeUpdate
    static hashPassword(user: User) {
        if (user.password) {            
            var salt = bcrypt.genSaltSync(saltRounds);
            user.password = bcrypt.hashSync(user.password, salt);
        }
    }
}
Now when I create a new user the model hashes the password and saves the hashed password in the table, but when I try to update the password of a user the password is saved in plain text. So I am guessing the @BeforeCreate works and the @BeforeUpdate hook does not.
I even tried separating the two hooks and giving them their own functions:
@BeforeCreate
static hashPasswordBeforeCreate(user: User) {
    if (user.password) {            
        var salt = bcrypt.genSaltSync(saltRounds);
        user.password = bcrypt.hashSync(user.password, salt);
    }
}
@BeforeUpdate
static hashPasswordBeforeUpdate(user: User) {
    if (user.password) {            
        var salt = bcrypt.genSaltSync(saltRounds);
        user.password = bcrypt.hashSync(user.password, salt);
    }
}
But the before update still does not work. What am I doing wrong?
I think you have to add
individualHooks: true
in your update query like this - users.update(data, {where: {id}, individualHooks: true});
Then, you can access the data into your @BeforeUpdate hook like this user.dataValues.
For ex.
@BeforeUpdate
static hashPasswordBeforeUpdate(user: User) {
        user.dataValues.password = bcrypt.hashSync(user.dataValues.password, salt);
}
This method works fine for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With