0
0
NestJSframework~30 mins

Custom providers in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating and Using Custom Providers in NestJS
📖 Scenario: You are building a simple NestJS application that needs to provide a greeting message. Instead of hardcoding the greeting, you want to use a custom provider to supply the greeting text. This approach helps keep your code flexible and easy to change later.
🎯 Goal: Build a NestJS module that uses a custom provider named GREETING to supply a greeting string. Then inject this provider into a service to return the greeting message.
📋 What You'll Learn
Create a custom provider named GREETING with the value 'Hello, NestJS!'
Create a service called GreetingService that injects the GREETING provider
Add a method getGreeting() in GreetingService that returns the injected greeting string
Register the custom provider and the service in a module called AppModule
💡 Why This Matters
🌍 Real World
Custom providers in NestJS allow you to inject values, classes, or factories that are not standard services. This is useful for configuration values, constants, or third-party libraries.
💼 Career
Understanding custom providers is essential for building scalable and maintainable NestJS applications, a skill often required for backend developer roles using Node.js and NestJS.
Progress0 / 4 steps
1
Create the custom provider with the greeting string
Create a constant called GREETING and set it to the string 'Hello, NestJS!'. Then create a provider object called greetingProvider with the key provide set to GREETING and useValue set to 'Hello, NestJS!'.
NestJS
Need a hint?

Remember, a custom provider in NestJS is an object with provide and useValue keys.

2
Create the GreetingService that injects the custom provider
Create a class called GreetingService. Use the @Injectable() decorator. Add a constructor that injects the GREETING provider using @Inject(GREETING) and stores it in a private readonly variable called greeting.
NestJS
Need a hint?

Use @Inject(GREETING) in the constructor parameter to inject the custom provider.

3
Add a method to return the greeting string
Inside the GreetingService class, add a method called getGreeting() that returns the private greeting string.
NestJS
Need a hint?

The method should simply return the injected greeting string.

4
Register the provider and service in AppModule
Create a class called AppModule with the @Module() decorator. Inside the decorator, add providers array containing greetingProvider and GreetingService. Export the AppModule class.
NestJS
Need a hint?

Use the @Module() decorator to register providers and services.