Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM check if column has changed

So, I'm using TypeORM with the ActiveRecord pattern and have this entity

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  public username: string;

  @Column()
  public password: string;

  @BeforeInsert()
  public async hashPassword() {
    this.password = await hashPassword(this.password);
  }

}

now what I want to accomplish is rehashing my password when any given User changes BUT only if the password field changed. I have seen some answers where I should store the tempPassword as a field in the User class but if for some reason the server goes down I would lose that data. I have also seen some people suggest the Subscriber thing typeorm has and im interested in that but not exactly sure how I would implement this with that. for reference this is how I would do what I want to do with mongoose

UserSchema.pre("save", function(next) {
  if (this.isModified("password") || this.isNew) {
    // hash the password
  }
})

any help is appreciated

like image 962
Skyler Brandt Avatar asked Oct 20 '25 11:10

Skyler Brandt


1 Answers

You can use AfterLoad decorator to store old password as a private temporary variable and compare it with the new password.

private tempPassword: string;
  @AfterLoad()
  storeOriginalPassword() {
    this.tempPassword = this.password;
  }

  @BeforeInsert()
  public async hashPassword() {
    if (this.password && this.password !== this.tempPassword) {
      this.password = await hashPassword(this.password);
    }
  }
like image 99
Sheikh Muhammad Umar Avatar answered Oct 23 '25 02:10

Sheikh Muhammad Umar