您如何检测 typeorm 中的密码等属性是否已更改

ade*_*ola 6 javascript node.js typeorm nestjs

在 typeorm 中,我试图在持久化到数据库之前使用订阅者装饰器来散列用户密码。不幸的是,我在文档中找不到参考。

在 sequelizejs 中,我使用以下代码,

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));
  };
Run Code Online (Sandbox Code Playgroud)

现在,我正在尝试将代码迁移到typeorm,我的翻译大致是

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

问题是,我停留在!user.changed('password'). 是否有等效的功能可以在typeorm不推出我自己的解决方案的情况下执行此操作?

Ala*_*405 5

在@adetoola's own issue 中找到了这个问题的解决方案。您可以使用@AfterLoad加载用户密码并检查当前密码是否不同:

@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) {
            //
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 这里需要注意的是,当使用像`.update()`和`.delete()`这样的存储库方法时,实体监听器不会被触发,因为实体没有被加载。如果您想确保这些方法触发,您需要加载实体(使用“.findOne()”),更新它,然后使用“.save()”方法。有关更多详细信息,请参阅[此 github 线程](https://github.com/typeorm/typeorm/issues/2036#issuecomment-385331765) (2认同)