0
0
NestJSframework~20 mins

Application lifecycle in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Application Lifecycle in NestJS
📖 Scenario: You are building a simple NestJS service that logs messages during different stages of the application lifecycle. This helps you understand how NestJS manages startup and shutdown events.
🎯 Goal: Create a NestJS service that uses lifecycle hooks to log messages when the application starts and stops.
📋 What You'll Learn
Create a service class named AppLifecycleService
Implement the OnModuleInit interface and its onModuleInit() method
Implement the OnModuleDestroy interface and its onModuleDestroy() method
Log 'Application has started' inside onModuleInit()
Log 'Application is shutting down' inside onModuleDestroy()
💡 Why This Matters
🌍 Real World
Understanding application lifecycle hooks helps developers run setup and cleanup code automatically in NestJS applications, such as connecting to databases or closing resources.
💼 Career
Many backend developer roles require knowledge of framework lifecycle events to manage resources efficiently and ensure smooth application startup and shutdown.
Progress0 / 4 steps
1
Create the service class
Create a class called AppLifecycleService and export it.
NestJS
Need a hint?

Use export class AppLifecycleService {} to create the class.

2
Add lifecycle interfaces
Import OnModuleInit and OnModuleDestroy from @nestjs/common. Then make AppLifecycleService implement both interfaces.
NestJS
Need a hint?

Use implements OnModuleInit, OnModuleDestroy after the class name.

3
Add lifecycle methods with logs
Inside AppLifecycleService, add the method onModuleInit() that logs 'Application has started'. Also add onModuleDestroy() that logs 'Application is shutting down'. Use console.log() for logging.
NestJS
Need a hint?

Define both methods exactly as named and use console.log with the exact messages.

4
Export the service for use
Ensure the AppLifecycleService class is exported so it can be used in other parts of the application.
NestJS
Need a hint?

Make sure the export keyword is before the class declaration.