Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect if an attribute like password has changed in typeorm

In typeorm, I am trying to use a subscriber decorator to hash users password before persisting to the database. Unfortunately, I can't find a reference in the docs.

In sequelizejs, I use the following code,

User.hashPassword = (user, options) => {
    if (!user.changed('password')) {
      return null;
    }
    // hash password
    return Bcrypt.hash(user.get('password'), SALT_ROUNDS)
      .then(hash => user.set('password', hash));
  };

Right now, I am trying to migrate the code to typeorm and my translation is roughly

@BeforeInsert()
@BeforeUpdate()
hashPassword() {
    // conditional to detect if password has changed goes here
    this.password = bcrypt.hashSync(this.password, SALT_ROUNDS);
}

The issue is, I stuck at !user.changed('password'). Is there an equivalent function in typeorm to do this without rolling out my own solution?

like image 363
adetoola Avatar asked Aug 05 '18 19:08

adetoola


1 Answers

The solution to this question was found in @adetoola's own issue. You can use @AfterLoad to load the user password and check if the current password is different:

@Entity()
export class User extends BaseEntity {
    @PrimaryColumn()
    public username: string;

    @Column()
    public password: string;

    @Column({ nullable: true })
    public jwtToken: string;

    private tempPassword: string;


    @AfterLoad()
    private loadTempPassword(): void {
        this.tempPassword = this.password;
    }

    @BeforeUpdate()
    private encryptPassword(): void {
        if (this.tempPassword !== this.password) {
            //
        }
    }
like image 76
Alain1405 Avatar answered Nov 09 '22 08:11

Alain1405