简体   繁体   中英

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

According to TypeOrm documentation, You can define a method with any name in the entity and mark it with @BeforeUpdate decorator and TypeORM will call it before an existing entity is updated using repository/manager save.

@BeforeUpdate()
  async updatePassword(): Promise<void> {
    this.password = await hashPassword(this.password);;
  }

You can check inside whatever you want, but I don't think it'll be necessary because if the password field is not changed it will be the same, and ORM will not update this column anyway. It'll only be updated if it's changed.

Mongoose provides us with the isModified() & isNew() methods because it does not handles the checks for you, you need to explicitly check if the field is actually modified or new.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM