0
0
NestJSframework~30 mins

Constructor injection in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Constructor Injection in NestJS
📖 Scenario: You are building a simple NestJS service that calculates discounts for products in an online store.To keep your code clean and testable, you will use constructor injection to provide the discount calculation logic to your service.
🎯 Goal: Create a NestJS service that uses constructor injection to receive a discount provider and applies it to product prices.
📋 What You'll Learn
Create a discount provider class with a method to calculate discount
Create a service class that receives the discount provider via constructor injection
Use the injected discount provider inside the service method to calculate discounted price
Export the service class properly for use in a NestJS module
💡 Why This Matters
🌍 Real World
Constructor injection is a common pattern in NestJS to manage dependencies like services, repositories, and providers cleanly.
💼 Career
Understanding constructor injection is essential for building scalable and maintainable backend applications with NestJS, a popular Node.js framework.
Progress0 / 4 steps
1
Create the DiscountProvider class
Create a class called DiscountProvider with a method getDiscount() that returns the number 0.1 (representing a 10% discount).
NestJS
Need a hint?

Think of DiscountProvider as a helper that tells how much discount to apply.

2
Create the PricingService class with constructor injection
Create a class called PricingService that has a constructor with a parameter called discountProvider of type DiscountProvider. Store this parameter in a private readonly property.
NestJS
Need a hint?

Use private readonly in the constructor parameter to automatically create and assign the property.

3
Add a method to calculate discounted price
Inside PricingService, add a method called calculatePrice that takes a price number parameter and returns the price after subtracting the discount. Use this.discountProvider.getDiscount() to get the discount rate.
NestJS
Need a hint?

Calculate the discounted price by subtracting price * discount from the original price.

4
Export the PricingService class
Make sure the PricingService class is exported so it can be used in other parts of the NestJS application.
NestJS
Need a hint?

Use export { PricingService }; to export the class explicitly.