In NestJS, providers are used to hold business logic. Why is this separation important?
Think about how separating concerns helps in managing code complexity and testing.
Providers encapsulate business logic to keep controllers simple and focused on handling requests. This separation improves code organization and makes testing business rules easier.
Consider a NestJS controller that contains complex business logic instead of delegating it to a provider. What is the likely outcome?
Think about code clarity and testing when logic is mixed in one place.
Putting business logic in controllers mixes responsibilities, making the code harder to maintain and test. Providers help keep these concerns separate.
When business logic is inside providers, how does this influence the way NestJS manages dependencies?
Consider how NestJS uses providers to share logic across the app.
Providers are designed to be injected wherever needed. This allows business logic to be reused and tested independently from controllers.
Choose the provider code snippet that properly encapsulates a simple business rule to calculate a discount.
export class DiscountService { calculate(price: number): number { if (price > 100) { return price * 0.9; } return price; } }
Look for correct TypeScript syntax and a method that always returns a number.
Option D uses correct syntax and always returns a number. Other options have syntax errors or missing return statements.
Given this provider code, why does NestJS throw an error when trying to inject it into a controller?
import { Injectable } from '@nestjs/common'; @Injectable() export class UserService { getUser() { return { id: 1, name: 'Alice' }; } }
Check if the class is properly marked for NestJS dependency injection.
In NestJS, providers must have the @Injectable() decorator to be recognized and injected. Missing it causes injection errors.