In NestJS, you can use lifecycle events to trigger methods when a module is shutting down. NestJS provides several hook functions that you can execute at different stages of the application's lifecycle. To perform certain operations when a module is shutting down, you can use the onModuleDestroy hook or the onApplicationShutdown hook.
onModuleDestroy Hook
The onModuleDestroy hook is a method provided by NestJS's OnModuleDestroy interface, called before the module is destroyed. To use it, your class must implement the OnModuleDestroy interface. This method is suitable for executing cleanup tasks but is not specific to application shutdown; it is tied to the module's lifecycle. It is invoked when the module is about to be destroyed.
typescriptimport { Injectable, OnModuleDestroy } from '@nestjs/common'; @Injectable() export class SomeService implements OnModuleDestroy { onModuleDestroy() { console.log('Cleaning up before the module is destroyed...'); // Implement your cleanup logic here } }
onApplicationShutdown Hook
The onApplicationShutdown hook is triggered before the application is about to be shut down. You can use it to perform shutdown preparations, such as gracefully closing database connections or other resources. To implement this hook, your service must implement NestJS's OnApplicationShutdown interface.
typescriptimport { Injectable, OnApplicationShutdown } from '@nestjs/common'; @Injectable() export class SomeService implements OnApplicationShutdown { onApplicationShutdown(signal?: string) { console.log(`Application is shutting down... Signal: ${signal}`); // Implement shutdown preparations here } }
Application Example
Suppose you have a service that needs to close a database connection when the application is shutting down. You can implement the onApplicationShutdown hook as follows:
typescriptimport { Injectable, OnApplicationShutdown } from '@nestjs/common'; import { DbService } from './db.service'; @Injectable() export class SomeService implements OnApplicationShutdown { constructor(private readonly dbService: DbService) {} onApplicationShutdown(signal?: string) { this.dbService.closeConnection(); console.log(`Database connection closed. Signal: ${signal}`); } }
Remember that for NestJS to call these hooks, your service must be injected into some module of the application. If the service is not utilized by any module, NestJS will not invoke these hooks even if they are implemented.