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