TypeORM uses Subscribers and Listeners to implement lifecycle hooks:
-
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 } } -
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); } } -
Available events:
- BeforeInsert / AfterInsert
- BeforeUpdate / AfterUpdate
- BeforeRemove / AfterRemove
- BeforeSoftRemove / AfterSoftRemove
- BeforeRecover / AfterRecover
- AfterLoad
-
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.