CodePark/ questions / Modules & architecture
START PRACTICINGPRACTICE
Backend question · NestJS › Modules & architecture

Explain the four properties of the @Module() decorator and how they relate to each other.

@Module({
  imports: [DatabaseModule],
  controllers: [CatsController],
  providers: [CatsService],
  exports: [CatsService],
})
export class CatsModule {}

The four properties are providers, controllers, imports and exports:

  • providers lists the classes (or custom providers) that the Nest injector creates for this module. By default, they are private to the module.
  • controllers lists the controllers this module defines. Nest creates them and registers their routes.
  • imports lists other modules whose exported providers this module needs.
  • exports is the part of this module's providers (or imported modules) that other modules can use when they import this module.

How they relate: the rule is encapsulation. A provider can only be injected inside its own module, unless the module exports it. The module that wants to use it must also import the module that exports it.

  • providers are created by the injector and are private by default.
  • controllers are the route handlers that the module owns.
  • imports lists the modules whose exports this module uses.
  • exports is the public API that other modules can inject.