Lifecycle Events trong NestJS

Lifecycle Events cho phép bạn hook vào các sự kiện quan trọng trong vòng đời của ứng dụng NestJS. Từ khởi tạo modules cho đến shutdown toàn bộ ứng dụng, NestJS cung cấp lifecycle hooks để bạn thực thi custom logic tại các thời điểm chính xác.

Các Lifecycle Hooks

NestJS cung cấp 8 lifecycle hooks chính:

1. OnModuleInit

Được gọi sau khi module được khởi tạo:
Khi sử dụng:
  • Khởi tạo kết nối database
  • Load configuration
  • Setup caching
  • Initialize external services

2. OnApplicationBootstrap

Được gọi sau khi tất cả modules đã khởi tạo và ứng dụng sẵn sàng:
Khi sử dụng:
  • Chạy migrations
  • Seed initial data
  • Start background jobs
  • Perform startup checks

3. OnModuleDestroy

Được gọi khi module bị hủy (ứng dụng tắt):
Khi sử dụng:
  • Đóng database connections
  • Release file handles
  • Cleanup temporary resources
  • Save state

4. BeforeApplicationShutdown

Được gọi trước khi ứng dụng tắt hoàn toàn:
Khi sử dụng:
  • Graceful shutdown
  • Save data before exit
  • Send notifications
  • Final cleanup

5. OnModuleInit (Async)

Async version của OnModuleInit:

6. OnApplicationShutdown

Được gọi cuối cùng trước khi process kết thúc:

Lifecycle Sequence

Ví Dụ Lifecycle Events Thực Tế

1. Database Connection Management

2. Cache Initialization and Cleanup

3. Migration Runner

4. Health Check Service

5. Background Job Scheduler

6. Configuration Loading

7. Logger Initialization

8. Graceful Shutdown Handler

9. Complete Application Lifecycle

Best Practices

1. Error Handling in Lifecycle Hooks

2. Implement Proper Cleanup

3. Log Lifecycle Events

4. Order Dependencies Properly

5. Use Signals for Graceful Shutdown

Complete Example

Kết Luận

Lifecycle Events là quan trọng để:
  • Initialize resources một cách an toàn
  • Perform startup checks trước khi chấp nhận requests
  • Clean up properly khi ứng dụng tắt
  • Implement graceful shutdown
  • Run migrations và seed data
Key Hooks:
  • OnModuleInit - Module initialization
  • OnApplicationBootstrap - All modules ready
  • BeforeApplicationShutdown - Graceful shutdown
  • OnModuleDestroy - Resource cleanup
Sử dụng lifecycle events đúng cách là essential để xây dựng robust, production-grade NestJS applications!