TypeORM @BeforeInsert() /@BeforeUpdate() 注解示例
@BeforeInsert() 和 @BeforeUpdate() 装饰器是 TypeORM 中非常有用的注解,它们可以让您在将实体保存到数据库之前修改实体的数据。以下是示例代码,演示如何使用这两个注解:
import { Entity, Column, PrimaryGeneratedColumn, BeforeInsert, BeforeUpdate } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ unique: true })
email: string;
@Column()
password: string;
@BeforeInsert()
@BeforeUpdate()
async hashPassword() {
// 将密码哈希
this.password = await hash(this.password, 10);
}
}
在上面的示例中,我们定义了一个名为 User 的实体,并在 password 字段上使用了 @BeforeInsert() 和 @BeforeUpdate() 装饰器。这些装饰器将 hashPassword() 方法绑定到相应的事件中。当您将实体保存到数据库之前或更新现有实体时,TypeORM 将自动调用此方法。
在我们的 hashPassword() 方法中,我们使用 bcrypt 库对密码进行哈希处理。由于这个方法被 @BeforeInsert() 和 @BeforeUpdate() 装饰器绑定了,因此每次创建新的实体或更新现有实体时,TypeORM 将自动调用该方法。因此,在将实体保存到数据库之前,它会将密码字段哈希化,这有助于保护用户的数据安全性。
注意,@BeforeInsert() 和 @BeforeUpdate() 装饰器也可以在实体上定义多个方法,这些方法将按定义的顺序调用。另外,这些方法也可以使用 Promise 来异步执行任何必要的操作