Node.js Framework Series— 1.1. NestJS — Lifecycle events

NestJS Lifecycle events

Lifecycle events usage

import { Injectable, OnModuleInit } from '@nestjs/common';
@Injectable()
export class AppService implements OnModuleInit {
onModuleInit() {
console.log(`The module has been initialised.`);
}
getHello(): string {
return 'Hello World!';
}
}
$ npm run start
..
[Nest] 10824 - 10/14/2020, 12:37:49 [RoutesResolver] ProfileController {/profile}: +0ms
The module has been initialized.
[Nest] 10824 - 10/14/2020, 12:37:49 [NestApplication] Nest application successfully started +3ms

Application shutdown

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Starts listening for shutdown hooks
app.enableShutdownHooks();
await app.listen(3000);
}
bootstrap();
import { Injectable, OnApplicationShutdown } from '@nestjs/common';@Injectable()
export class AppService implements OnApplicationShutdown {
onApplicationShutdown(signal: string) {
console.log('Application is shutdown.'); // e.g. "SIGINT"
console.log(signal); // e.g. "SIGINT"
}
getHello(): string {
return 'Hello World!';
}
}
[Nest] 11094   - 10/14/2020, 13:03:10   [NestApplication] Nest application successfully started +1ms^CApplication is shutdown.
SIGINT

Technical Training Coordinator at www.Zero2Hero.Training, Blockchain Developer(Oxford BC Strategy Programme Certified) and an AWS Certified Solution Architect.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store