# 监听器与订阅者

> 英文标题：Listeners and Subscribers
> 官网原文：https://typeorm.io/docs/listeners-and-subscribers
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 50 块

---

<!-- EN -->
# Listeners and Subscribers

<!-- ZH -->
# 监听器与订阅者

<!-- EN -->
## What is an Entity Listener?

<!-- ZH -->
## 什么是实体监听器？

<!-- EN -->
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.

<!-- ZH -->
你的任何实体都可以带有包含自定义逻辑的方法，用来监听特定的实体事件。你必须根据想监听的事件，用特殊的装饰器标记这些方法。

<!-- EN -->
**Note:** Do not make any database calls within a listener, opt for [subscribers](#what-is-a-subscriber) instead.

<!-- ZH -->
**注意：** 不要在监听器中进行任何数据库调用，请改用[订阅者](#what-is-a-subscriber)。

<!-- EN -->
### `@AfterLoad`

<!-- ZH -->
### `@AfterLoad`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterLoad` 标记它，每当该实体通过 `QueryBuilder` 或 repository/manager 的 find 方法被加载时，TypeORM 都会调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterLoad()
    updateCounters() {
        if (this.likesCount === undefined) this.likesCount = 0
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterLoad()
    updateCounters() {
        if (this.likesCount === undefined) this.likesCount = 0
    }
}
```

<!-- EN -->
### `@BeforeInsert`

<!-- ZH -->
### `@BeforeInsert`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeInsert` 标记它，TypeORM 会在该实体通过 repository/manager 的 `save` 被插入之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeInsert()
    updateDates() {
        this.createdDate = new Date()
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeInsert()
    updateDates() {
        this.createdDate = new Date()
    }
}
```

<!-- EN -->
### `@AfterInsert`

<!-- ZH -->
### `@AfterInsert`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterInsert` 标记它，TypeORM 会在该实体通过 repository/manager 的 `save` 被插入之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterInsert()
    resetCounters() {
        this.counters = 0
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterInsert()
    resetCounters() {
        this.counters = 0
    }
}
```

<!-- EN -->
### `@BeforeUpdate`

<!-- ZH -->
### `@BeforeUpdate`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeUpdate` 标记它，TypeORM 会在已有实体通过 repository/manager 的 `save` 被更新之前调用它。不过请记住，只有模型中的信息发生了变化时才会触发。如果你在没有修改模型任何内容的情况下运行 `save`，`@BeforeUpdate` 和 `@AfterUpdate` 都不会运行。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeUpdate()
    updateDates() {
        this.updatedDate = new Date()
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeUpdate()
    updateDates() {
        this.updatedDate = new Date()
    }
}
```

<!-- EN -->
### `@AfterUpdate`

<!-- ZH -->
### `@AfterUpdate`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterUpdate` 标记它，TypeORM 会在已有实体通过 repository/manager 的 `save` 被更新之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterUpdate()
    updateCounters() {
        this.counter = 0
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterUpdate()
    updateCounters() {
        this.counter = 0
    }
}
```

<!-- EN -->
### `@BeforeRemove`

<!-- ZH -->
### `@BeforeRemove`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeRemove` 标记它，TypeORM 会在该实体通过 repository/manager 的 `remove` 被移除之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeRemove()
    updateStatus() {
        this.status = "removed"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeRemove()
    updateStatus() {
        this.status = "removed"
    }
}
```

<!-- EN -->
### `@AfterRemove`

<!-- ZH -->
### `@AfterRemove`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterRemove` 标记它，TypeORM 会在该实体通过 repository/manager 的 `remove` 被移除之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterRemove()
    updateStatus() {
        this.status = "removed"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterRemove()
    updateStatus() {
        this.status = "removed"
    }
}
```

<!-- EN -->
### `@BeforeSoftRemove`

<!-- ZH -->
### `@BeforeSoftRemove`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeSoftRemove` 标记它，TypeORM 会在该实体通过 repository/manager 的 `softRemove` 被软删除之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeSoftRemove()
    updateStatus() {
        this.status = "soft-removed"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeSoftRemove()
    updateStatus() {
        this.status = "soft-removed"
    }
}
```

<!-- EN -->
### `@AfterSoftRemove`

<!-- ZH -->
### `@AfterSoftRemove`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterSoftRemove` 标记它，TypeORM 会在该实体通过 repository/manager 的 `softRemove` 被软删除之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterSoftRemove()
    updateStatus() {
        this.status = "soft-removed"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterSoftRemove()
    updateStatus() {
        this.status = "soft-removed"
    }
}
```

<!-- EN -->
### `@BeforeRecover`

<!-- ZH -->
### `@BeforeRecover`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeRecover` 标记它，TypeORM 会在该实体通过 repository/manager 的 `recover` 被恢复之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeRecover()
    updateStatus() {
        this.status = "recovered"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeRecover()
    updateStatus() {
        this.status = "recovered"
    }
}
```

<!-- EN -->
### `@AfterRecover`

<!-- ZH -->
### `@AfterRecover`

<!-- EN -->
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:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterRecover` 标记它，TypeORM 会在该实体通过 repository/manager 的 `recover` 被恢复之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterRecover()
    updateStatus() {
        this.status = "recovered"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterRecover()
    updateStatus() {
        this.status = "recovered"
    }
}
```

<!-- EN -->
## What is a Subscriber?

<!-- ZH -->
## 什么是订阅者？

<!-- EN -->
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:

<!-- ZH -->
把一个类标记为事件订阅者，它可以监听特定实体的事件或任意实体的事件。事件通过 `QueryBuilder` 和 repository/manager 方法触发。示例：

<!-- EN -->
```typescript
@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)
    }
}
```

<!-- ZH -->
```typescript
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface<Post> {
    /**
     * 表示该订阅者只监听 Post 事件。
     */
    listenTo() {
        return Post
    }

    /**
     * 在 post 插入之前调用。
     */
    beforeInsert(event: InsertEvent<Post>) {
        console.log(`BEFORE POST INSERTED: `, event.entity)
    }
}
```

<!-- EN -->
You can implement any method from `EntitySubscriberInterface`. To listen to any entity you just omit `listenTo` method and use `any`:

<!-- ZH -->
你可以实现 `EntitySubscriberInterface` 中的任意方法。要监听任意实体，只需省略 `listenTo` 方法并使用 `any`：

<!-- EN -->
```typescript
@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)
    }
}
```

<!-- ZH -->
```typescript
@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)
    }
}
```

<!-- EN -->
Make sure your `subscribers` property is set in your [DataSourceOptions](https://typeorm.io/docs/data-source/data-source-options#common-data-source-options) so TypeORM loads your subscriber.

<!-- ZH -->
请确保在你的 [DataSourceOptions](https://typeorm.io/docs/data-source/data-source-options#common-data-source-options) 中设置了 `subscribers` 属性，这样 TypeORM 才会加载你的订阅者。

<!-- EN -->
### `Event Object`

<!-- ZH -->
### `事件对象`

<!-- EN -->
Excluding `listenTo`, all `EntitySubscriberInterface` methods are passed an event object that has the following base properties:

<!-- ZH -->
除 `listenTo` 之外，所有 `EntitySubscriberInterface` 方法都会收到一个事件对象，它具有以下基础属性：

<!-- EN -->
* `dataSource: DataSource` - DataSource used in the event.
* `queryRunner: QueryRunner` - QueryRunner used in the event transaction.
* `manager: EntityManager` - EntityManager used in the event transaction.

<!-- ZH -->
* `dataSource: DataSource` - 事件中所使用的 DataSource。
* `queryRunner: QueryRunner` - 事件事务中所使用的 QueryRunner。
* `manager: EntityManager` - 事件事务中所使用的 EntityManager。

<!-- EN -->
See each [Event's interface](https://github.com/typeorm/typeorm/tree/master/packages/typeorm/src/subscriber/event) for additional properties.

<!-- ZH -->
更多属性请参阅各[事件接口](https://github.com/typeorm/typeorm/tree/master/packages/typeorm/src/subscriber/event)。

<!-- EN -->
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.

<!-- ZH -->
注意，使用 `Repository.update()` 时，`event.entity` 未必包含主键。只有作为实体部分提供的那些值可用。为了让订阅者中能拿到主键，你可以在部分实体对象字面量中显式传入主键值，或者使用会重新取回数据的 `Repository.save()`。

<!-- EN -->
```typescript
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' }
}
```

<!-- ZH -->
```typescript
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' }
}
```

<!-- EN -->
**Note:** All database operations in the subscribed event listeners should be performed using the event object's `queryRunner` or `manager` instance.

<!-- ZH -->
**注意：** 在被订阅的事件监听器中，所有数据库操作都应使用事件对象的 `queryRunner` 或 `manager` 实例来执行。
