乐闻世界logo
搜索文章和话题

How to use lifecycle hooks in TypeORM?

2月17日 22:48

TypeORM uses Subscribers and Listeners to implement lifecycle hooks:

  1. Entity Listeners: Define listeners in the entity class using decorators:

    typescript
    @Entity() export class User { @BeforeInsert() beforeInsert() { this.createdAt = new Date(); } @BeforeUpdate() beforeUpdate() { this.updatedAt = new Date(); } @AfterLoad() afterLoad() { // Execute after loading } }
  2. Subscribers: Independent classes that can listen to lifecycle events of multiple entities:

    typescript
    @EventSubscriber() export class UserSubscriber implements EntitySubscriberInterface<User> { listenTo() { return User; } beforeInsert(event: InsertEvent<User>) { console.log('Before insert:', event.entity); } }
  3. Available events:

    • BeforeInsert / AfterInsert
    • BeforeUpdate / AfterUpdate
    • BeforeRemove / AfterRemove
    • BeforeSoftRemove / AfterSoftRemove
    • BeforeRecover / AfterRecover
    • AfterLoad
  4. Register subscribers: Add the subscribers option in the DataSource configuration.

Lifecycle hooks are suitable for scenarios such as data validation, auto-filling fields, logging, etc.

标签:TypeORM