0
0
NestJSframework~30 mins

Dynamic modules in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating a Dynamic Module in NestJS
📖 Scenario: You are building a NestJS application that needs a configurable logging module. This module should allow different parts of the app to use it with custom settings.
🎯 Goal: Create a dynamic module called LoggerModule that accepts a configuration object with a logLevel property. This module should provide a LoggerService that uses the configured logLevel.
📋 What You'll Learn
Create a LoggerModule class with a static forRoot method that accepts a config object with logLevel string property.
Inside forRoot, return a dynamic module with module, providers, and exports properties.
Create a LoggerService class that uses the injected logLevel to control logging.
Use NestJS dependency injection to provide the logLevel value to LoggerService.
💡 Why This Matters
🌍 Real World
Dynamic modules let you build reusable NestJS modules that can be configured differently in various parts of your app, like database connections or logging.
💼 Career
Understanding dynamic modules is essential for building scalable and maintainable NestJS applications in professional backend development.
Progress0 / 4 steps
1
Create the LoggerModule class with forRoot method
Create a class called LoggerModule with a static method forRoot that accepts a parameter options of type { logLevel: string }. The method should return an object with a module property set to LoggerModule.
NestJS
Need a hint?

Define a class and a static method that returns an object with a module property.

2
Add provider for logLevel token
Inside the forRoot method of LoggerModule, add a providers array to the returned object. This array should contain an object with provide set to 'LOG_LEVEL' and useValue set to options.logLevel. Also add exports array with 'LOG_LEVEL'.
NestJS
Need a hint?

Add providers and exports arrays to the returned object in forRoot.

3
Create LoggerService using injected logLevel
Create a class called LoggerService with a constructor that injects logLevel using @Inject('LOG_LEVEL'). Store it in a private readonly property called logLevel. Add a method log that accepts a message string and logs it only if logLevel is not 'none'.
NestJS
Need a hint?

Use @Inject('LOG_LEVEL') in the constructor to get the log level value.

4
Add LoggerService provider and export to LoggerModule
In the forRoot method of LoggerModule, add LoggerService to the providers array and also add it to the exports array.
NestJS
Need a hint?

Add LoggerService to both providers and exports arrays in forRoot.