NestJS NestJS Architecture & Design Patterns 2 — Questions and Answers
Question 1: Which decorator transforms a plain class into a NestJS injectable service?
- @Service()
- @Provider()
- @Injectable() (Correct answer)
- @Singleton()
Correct answer: @Injectable()
@Injectable() marks a class as a provider that the NestJS IoC container can instantiate and inject into other classes.
Question 2: What is a Dynamic Module in NestJS?
- A module loaded at runtime via lazy loading
- A module that exports configuration-based providers at import time (Correct answer)
- A module with runtime-generated controllers
- A module that dynamically creates routes
Correct answer: A module that exports configuration-based providers at import time
A Dynamic Module returns a module configuration object (including providers) at import time, enabling customizable, reusable modules like ConfigModule.forRoot().
Question 3: Which SOLID principle is most directly enforced by NestJS's dependency injection system?
- Single Responsibility
- Open/Closed
- Dependency Inversion (Correct answer)
- Interface Segregation
Correct answer: Dependency Inversion
NestJS DI enforces the Dependency Inversion Principle by having high-level modules depend on abstractions (tokens/interfaces) rather than concrete implementations.
Question 4: How do you create a circular dependency between two NestJS providers without causing errors?
- Use @Inject() with lazy references
- Use forwardRef() in both @Inject() decorators (Correct answer)
- Use a shared Global module
- Circular dependencies are impossible in NestJS
Correct answer: Use forwardRef() in both @Inject() decorators
forwardRef() wraps the class reference to defer its resolution, allowing NestJS to break the circular dependency loop during instantiation.
Question 5: What does the `imports` array in @Module() accept?
- NPM package names
- Other module classes whose exported providers are needed (Correct answer)
- Service class references
- Middleware functions
Correct answer: Other module classes whose exported providers are needed
The `imports` array takes other NestJS module classes, making their exported providers available for injection within the importing module.
Question 6: Which NestJS architectural concept is analogous to Angular's NgModule?
- Controller
- Provider
- Module (Correct answer)
- Guard
Correct answer: Module
NestJS Module (decorated with @Module()) mirrors Angular's NgModule concept, serving as a cohesive block of related functionality.
Which decorator transforms a plain class into a NestJS injectable service?