监听器与订阅者
什么是实体监听器?
你的任何实体都可以带有包含自定义逻辑的方法,用来监听特定的实体事件。你必须根据想监听的事件,用特殊的装饰器标记这些方法。
注意: 不要在监听器中进行任何数据库调用,请改用订阅者。
@AfterLoad
你可以在实体中定义一个任意名称的方法并用 @AfterLoad 标记它,每当该实体通过 QueryBuilder 或 repository/manager 的 find 方法被加载时,TypeORM 都会调用它。示例:
@Entity()
export class Post {
@AfterLoad()
updateCounters() {
if (this.likesCount === undefined) this.likesCount = 0
}
}@BeforeInsert
你可以在实体中定义一个任意名称的方法并用 @BeforeInsert 标记它,TypeORM 会在该实体通过 repository/manager 的 save 被插入之前调用它。示例:
@Entity()
export class Post {
@BeforeInsert()
updateDates() {
this.createdDate = new Date()
}
}@AfterInsert
你可以在实体中定义一个任意名称的方法并用 @AfterInsert 标记它,TypeORM 会在该实体通过 repository/manager 的 save 被插入之后调用它。示例:
@Entity()
export class Post {
@AfterInsert()
resetCounters() {
this.counters = 0
}
}@BeforeUpdate
你可以在实体中定义一个任意名称的方法并用 @BeforeUpdate 标记它,TypeORM 会在已有实体通过 repository/manager 的 save 被更新之前调用它。不过请记住,只有模型中的信息发生了变化时才会触发。如果你在没有修改模型任何内容的情况下运行 save,@BeforeUpdate 和 @AfterUpdate 都不会运行。示例:
@Entity()
export class Post {
@BeforeUpdate()
updateDates() {
this.updatedDate = new Date()
}
}@AfterUpdate
你可以在实体中定义一个任意名称的方法并用 @AfterUpdate 标记它,TypeORM 会在已有实体通过 repository/manager 的 save 被更新之后调用它。示例:
@Entity()
export class Post {
@AfterUpdate()
updateCounters() {
this.counter = 0
}
}@BeforeRemove
你可以在实体中定义一个任意名称的方法并用 @BeforeRemove 标记它,TypeORM 会在该实体通过 repository/manager 的 remove 被移除之前调用它。示例:
@Entity()
export class Post {
@BeforeRemove()
updateStatus() {
this.status = "removed"
}
}@AfterRemove
你可以在实体中定义一个任意名称的方法并用 @AfterRemove 标记它,TypeORM 会在该实体通过 repository/manager 的 remove 被移除之后调用它。示例:
@Entity()
export class Post {
@AfterRemove()
updateStatus() {
this.status = "removed"
}
}@BeforeSoftRemove
你可以在实体中定义一个任意名称的方法并用 @BeforeSoftRemove 标记它,TypeORM 会在该实体通过 repository/manager 的 softRemove 被软删除之前调用它。示例:
@Entity()
export class Post {
@BeforeSoftRemove()
updateStatus() {
this.status = "soft-removed"
}
}@AfterSoftRemove
你可以在实体中定义一个任意名称的方法并用 @AfterSoftRemove 标记它,TypeORM 会在该实体通过 repository/manager 的 softRemove 被软删除之后调用它。示例:
@Entity()
export class Post {
@AfterSoftRemove()
updateStatus() {
this.status = "soft-removed"
}
}@BeforeRecover
你可以在实体中定义一个任意名称的方法并用 @BeforeRecover 标记它,TypeORM 会在该实体通过 repository/manager 的 recover 被恢复之前调用它。示例:
@Entity()
export class Post {
@BeforeRecover()
updateStatus() {
this.status = "recovered"
}
}@AfterRecover
你可以在实体中定义一个任意名称的方法并用 @AfterRecover 标记它,TypeORM 会在该实体通过 repository/manager 的 recover 被恢复之后调用它。示例:
@Entity()
export class Post {
@AfterRecover()
updateStatus() {
this.status = "recovered"
}
}什么是订阅者?
把一个类标记为事件订阅者,它可以监听特定实体的事件或任意实体的事件。事件通过 QueryBuilder 和 repository/manager 方法触发。示例:
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface<Post> {
/**
* 表示该订阅者只监听 Post 事件。
*/
listenTo() {
return Post
}
/**
* 在 post 插入之前调用。
*/
beforeInsert(event: InsertEvent<Post>) {
console.log(`BEFORE POST INSERTED: `, event.entity)
}
}你可以实现 EntitySubscriberInterface 中的任意方法。要监听任意实体,只需省略 listenTo 方法并使用 any:
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface {
/**
* 在实体加载之后调用。
*/
afterLoad(entity: any) {
console.log(`AFTER ENTITY LOADED: `, entity)
}
/**
* 在查询执行之前调用。
*/
beforeQuery(event: BeforeQueryEvent) {
console.log(`BEFORE QUERY: `, event.query)
}
/**
* 在查询执行之后调用。
*/
afterQuery(event: AfterQueryEvent) {
console.log(`AFTER QUERY: `, event.query)
}
/**
* 在实体插入之前调用。
*/
beforeInsert(event: InsertEvent<any>) {
console.log(`BEFORE ENTITY INSERTED: `, event.entity)
}
/**
* 在实体插入之后调用。
*/
afterInsert(event: InsertEvent<any>) {
console.log(`AFTER ENTITY INSERTED: `, event.entity)
}
/**
* 在实体更新之前调用。
*/
beforeUpdate(event: UpdateEvent<any>) {
console.log(`BEFORE ENTITY UPDATED: `, event.entity)
}
/**
* 在实体更新之后调用。
*/
afterUpdate(event: UpdateEvent<any>) {
console.log(`AFTER ENTITY UPDATED: `, event.entity)
}
/**
* 在实体移除之前调用。
*/
beforeRemove(event: RemoveEvent<any>) {
console.log(
`BEFORE ENTITY WITH ID ${event.entityId} REMOVED: `,
event.entity,
)
}
/**
* 在实体移除之后调用。
*/
afterRemove(event: RemoveEvent<any>) {
console.log(
`AFTER ENTITY WITH ID ${event.entityId} REMOVED: `,
event.entity,
)
}
/**
* 在实体移除之前调用。
*/
beforeSoftRemove(event: SoftRemoveEvent<any>) {
console.log(
`BEFORE ENTITY WITH ID ${event.entityId} SOFT REMOVED: `,
event.entity,
)
}
/**
* 在实体移除之后调用。
*/
afterSoftRemove(event: SoftRemoveEvent<any>) {
console.log(
`AFTER ENTITY WITH ID ${event.entityId} SOFT REMOVED: `,
event.entity,
)
}
/**
* 在实体恢复之前调用。
*/
beforeRecover(event: RecoverEvent<any>) {
console.log(
`BEFORE ENTITY WITH ID ${event.entityId} RECOVERED: `,
event.entity,
)
}
/**
* 在实体恢复之后调用。
*/
afterRecover(event: RecoverEvent<any>) {
console.log(
`AFTER ENTITY WITH ID ${event.entityId} RECOVERED: `,
event.entity,
)
}
/**
* 在事务开始之前调用。
*/
beforeTransactionStart(event: TransactionStartEvent) {
console.log(`BEFORE TRANSACTION STARTED: `, event)
}
/**
* 在事务开始之后调用。
*/
afterTransactionStart(event: TransactionStartEvent) {
console.log(`AFTER TRANSACTION STARTED: `, event)
}
/**
* 在事务提交之前调用。
*/
beforeTransactionCommit(event: TransactionCommitEvent) {
console.log(`BEFORE TRANSACTION COMMITTED: `, event)
}
/**
* 在事务提交之后调用。
*/
afterTransactionCommit(event: TransactionCommitEvent) {
console.log(`AFTER TRANSACTION COMMITTED: `, event)
}
/**
* 在事务回滚之前调用。
*/
beforeTransactionRollback(event: TransactionRollbackEvent) {
console.log(`BEFORE TRANSACTION ROLLBACK: `, event)
}
/**
* 在事务回滚之后调用。
*/
afterTransactionRollback(event: TransactionRollbackEvent) {
console.log(`AFTER TRANSACTION ROLLBACK: `, event)
}
}请确保在你的 DataSourceOptions 中设置了 subscribers 属性,这样 TypeORM 才会加载你的订阅者。
事件对象
除 listenTo 之外,所有 EntitySubscriberInterface 方法都会收到一个事件对象,它具有以下基础属性:
dataSource: DataSource- 事件中所使用的 DataSource。queryRunner: QueryRunner- 事件事务中所使用的 QueryRunner。manager: EntityManager- 事件事务中所使用的 EntityManager。
更多属性请参阅各事件接口。
注意,使用 Repository.update() 时,event.entity 未必包含主键。只有作为实体部分提供的那些值可用。为了让订阅者中能拿到主键,你可以在部分实体对象字面量中显式传入主键值,或者使用会重新取回数据的 Repository.save()。
await postRepository.update(post.id, { description: "Bacon ipsum dolor amet cow" })
// post.subscriber.ts
afterUpdate(event: UpdateEvent<Post>) {
console.log(event.entity) // 输出 { description: 'Bacon ipsum dolor amet cow' }
}注意: 在被订阅的事件监听器中,所有数据库操作都应使用事件对象的 queryRunner 或 manager 实例来执行。
What is an Entity Listener?
Any of your entities can have methods with custom logic that listen to specific entity events. You must mark those methods with special decorators depending on what event you want to listen to.
Note: Do not make any database calls within a listener, opt for subscribers instead.
@AfterLoad
You can define a method with any name in entity and mark it with @AfterLoad and TypeORM will call it each time the entity is loaded using QueryBuilder or repository/manager find methods. Example:
@Entity()
export class Post {
@AfterLoad()
updateCounters() {
if (this.likesCount === undefined) this.likesCount = 0
}
}@BeforeInsert
You can define a method with any name in entity and mark it with @BeforeInsert and TypeORM will call it before the entity is inserted using repository/manager save. Example:
@Entity()
export class Post {
@BeforeInsert()
updateDates() {
this.createdDate = new Date()
}
}@AfterInsert
You can define a method with any name in entity and mark it with @AfterInsert and TypeORM will call it after the entity is inserted using repository/manager save. Example:
@Entity()
export class Post {
@AfterInsert()
resetCounters() {
this.counters = 0
}
}@BeforeUpdate
You can define a method with any name in the entity and mark it with @BeforeUpdate and TypeORM will call it before an existing entity is updated using repository/manager save. Keep in mind, however, that this will occur only when information is changed in the model. If you run save without modifying anything from the model, @BeforeUpdate and @AfterUpdate will not run. Example:
@Entity()
export class Post {
@BeforeUpdate()
updateDates() {
this.updatedDate = new Date()
}
}@AfterUpdate
You can define a method with any name in the entity and mark it with @AfterUpdate and TypeORM will call it after an existing entity is updated using repository/manager save. Example:
@Entity()
export class Post {
@AfterUpdate()
updateCounters() {
this.counter = 0
}
}@BeforeRemove
You can define a method with any name in the entity and mark it with @BeforeRemove and TypeORM will call it before an entity is removed using repository/manager remove. Example:
@Entity()
export class Post {
@BeforeRemove()
updateStatus() {
this.status = "removed"
}
}@AfterRemove
You can define a method with any name in the entity and mark it with @AfterRemove and TypeORM will call it after the entity is removed using repository/manager remove. Example:
@Entity()
export class Post {
@AfterRemove()
updateStatus() {
this.status = "removed"
}
}@BeforeSoftRemove
You can define a method with any name in the entity and mark it with @BeforeSoftRemove and TypeORM will call it before an entity is soft removed using repository/manager softRemove. Example:
@Entity()
export class Post {
@BeforeSoftRemove()
updateStatus() {
this.status = "soft-removed"
}
}@AfterSoftRemove
You can define a method with any name in the entity and mark it with @AfterSoftRemove and TypeORM will call it after the entity is soft removed using repository/manager softRemove. Example:
@Entity()
export class Post {
@AfterSoftRemove()
updateStatus() {
this.status = "soft-removed"
}
}@BeforeRecover
You can define a method with any name in the entity and mark it with @BeforeRecover and TypeORM will call it before an entity is recovered using repository/manager recover. Example:
@Entity()
export class Post {
@BeforeRecover()
updateStatus() {
this.status = "recovered"
}
}@AfterRecover
You can define a method with any name in the entity and mark it with @AfterRecover and TypeORM will call it after the entity is recovered using repository/manager recover. Example:
@Entity()
export class Post {
@AfterRecover()
updateStatus() {
this.status = "recovered"
}
}What is a Subscriber?
Marks a class as an event subscriber which can listen to specific entity events or any entity events. Events are firing using QueryBuilder and repository/manager methods. Example:
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface<Post> {
/**
* Indicates that this subscriber only listen to Post events.
*/
listenTo() {
return Post
}
/**
* Called before post insertion.
*/
beforeInsert(event: InsertEvent<Post>) {
console.log(`BEFORE POST INSERTED: `, event.entity)
}
}You can implement any method from EntitySubscriberInterface. To listen to any entity you just omit listenTo method and use any:
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface {
/**
* Called after entity is loaded.
*/
afterLoad(entity: any) {
console.log(`AFTER ENTITY LOADED: `, entity)
}
/**
* Called before query execution.
*/
beforeQuery(event: BeforeQueryEvent) {
console.log(`BEFORE QUERY: `, event.query)
}
/**
* Called after query execution.
*/
afterQuery(event: AfterQueryEvent) {
console.log(`AFTER QUERY: `, event.query)
}
/**
* Called before entity insertion.
*/
beforeInsert(event: InsertEvent<any>) {
console.log(`BEFORE ENTITY INSERTED: `, event.entity)
}
/**
* Called after entity insertion.
*/
afterInsert(event: InsertEvent<any>) {
console.log(`AFTER ENTITY INSERTED: `, event.entity)
}
/**
* Called before entity update.
*/
beforeUpdate(event: UpdateEvent<any>) {
console.log(`BEFORE ENTITY UPDATED: `, event.entity)
}
/**
* Called after entity update.
*/
afterUpdate(event: UpdateEvent<any>) {
console.log(`AFTER ENTITY UPDATED: `, event.entity)
}
/**
* Called before entity removal.
*/
beforeRemove(event: RemoveEvent<any>) {
console.log(
`BEFORE ENTITY WITH ID ${event.entityId} REMOVED: `,
event.entity,
)
}
/**
* Called after entity removal.
*/
afterRemove(event: RemoveEvent<any>) {
console.log(
`AFTER ENTITY WITH ID ${event.entityId} REMOVED: `,
event.entity,
)
}
/**
* Called before entity removal.
*/
beforeSoftRemove(event: SoftRemoveEvent<any>) {
console.log(
`BEFORE ENTITY WITH ID ${event.entityId} SOFT REMOVED: `,
event.entity,
)
}
/**
* Called after entity removal.
*/
afterSoftRemove(event: SoftRemoveEvent<any>) {
console.log(
`AFTER ENTITY WITH ID ${event.entityId} SOFT REMOVED: `,
event.entity,
)
}
/**
* Called before entity recovery.
*/
beforeRecover(event: RecoverEvent<any>) {
console.log(
`BEFORE ENTITY WITH ID ${event.entityId} RECOVERED: `,
event.entity,
)
}
/**
* Called after entity recovery.
*/
afterRecover(event: RecoverEvent<any>) {
console.log(
`AFTER ENTITY WITH ID ${event.entityId} RECOVERED: `,
event.entity,
)
}
/**
* Called before transaction start.
*/
beforeTransactionStart(event: TransactionStartEvent) {
console.log(`BEFORE TRANSACTION STARTED: `, event)
}
/**
* Called after transaction start.
*/
afterTransactionStart(event: TransactionStartEvent) {
console.log(`AFTER TRANSACTION STARTED: `, event)
}
/**
* Called before transaction commit.
*/
beforeTransactionCommit(event: TransactionCommitEvent) {
console.log(`BEFORE TRANSACTION COMMITTED: `, event)
}
/**
* Called after transaction commit.
*/
afterTransactionCommit(event: TransactionCommitEvent) {
console.log(`AFTER TRANSACTION COMMITTED: `, event)
}
/**
* Called before transaction rollback.
*/
beforeTransactionRollback(event: TransactionRollbackEvent) {
console.log(`BEFORE TRANSACTION ROLLBACK: `, event)
}
/**
* Called after transaction rollback.
*/
afterTransactionRollback(event: TransactionRollbackEvent) {
console.log(`AFTER TRANSACTION ROLLBACK: `, event)
}
}Make sure your subscribers property is set in your DataSourceOptions so TypeORM loads your subscriber.
Event Object
Excluding listenTo, all EntitySubscriberInterface methods are passed an event object that has the following base properties:
dataSource: DataSource- DataSource used in the event.queryRunner: QueryRunner- QueryRunner used in the event transaction.manager: EntityManager- EntityManager used in the event transaction.
See each Event's interface for additional properties.
Note that event.entity may not necessarily contain primary key(s) when Repository.update() is used. Only the values provided as the entity partial will be available. In order to make primary keys available in the subscribers, you can explicitly pass primary key value(s) in the partial entity object literal or use Repository.save(), which performs re-fetching.
await postRepository.update(post.id, { description: "Bacon ipsum dolor amet cow" })
// post.subscriber.ts
afterUpdate(event: UpdateEvent<Post>) {
console.log(event.entity) // outputs { description: 'Bacon ipsum dolor amet cow' }
}Note: All database operations in the subscribed event listeners should be performed using the event object's queryRunner or manager instance.