0
0
NestJSframework~30 mins

Optional providers in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Optional Providers in NestJS
📖 Scenario: You are building a NestJS service that optionally uses a logger service if it is provided. This is common when you want to add extra features without forcing them.
🎯 Goal: Create a NestJS service that optionally injects a LoggerService. If the logger is provided, the service uses it to log messages; if not, it works without errors.
📋 What You'll Learn
Create a LoggerService class with a log(message: string) method.
Create a MyService class that optionally injects LoggerService using @Optional().
In MyService, add a method doWork() that calls logger.log() only if the logger exists.
Set up a NestJS module that provides MyService and optionally provides LoggerService.
💡 Why This Matters
🌍 Real World
Optional providers are useful when you want to add features like logging, caching, or analytics only if they are configured, without forcing all parts of the app to depend on them.
💼 Career
Understanding optional providers helps you write flexible and maintainable NestJS applications that can adapt to different environments and requirements.
Progress0 / 4 steps
1
Create LoggerService class
Create a class called LoggerService with a method log(message: string) that does nothing inside.
NestJS
Need a hint?

Define a class with a method named log that accepts a message string parameter.

2
Create MyService with optional LoggerService injection
Create a class called MyService with a constructor that optionally injects LoggerService using @Optional() and @Inject() decorators from @nestjs/common. Store it in a private readonly property called logger.
NestJS
Need a hint?

Use @Optional() and @Inject(LoggerService) before the constructor parameter logger.

3
Add doWork method using optional logger
In the MyService class, add a method called doWork() that calls this.logger.log('Work done') only if this.logger exists.
NestJS
Need a hint?

Check if this.logger is truthy before calling log.

4
Create module with optional LoggerService provider
Create a NestJS module class called AppModule that provides MyService. Also add LoggerService to the providers array but comment it out to simulate optional provision.
NestJS
Need a hint?

Use @Module decorator with a providers array including MyService and a commented out LoggerService.