The @Module decorator helps organize your NestJS app by grouping related parts together. It tells NestJS what controllers, providers, and other modules belong to this group.
0
0
Module decorator and metadata in NestJS
Introduction
When you want to group related controllers and services for a feature.
When you need to import other modules to use their services.
When you want to keep your app organized and easy to maintain.
When you want to share providers between different parts of your app.
When you want to define the main app module that starts your application.
Syntax
NestJS
@Module({
imports: [],
controllers: [],
providers: [],
exports: []
})
export class YourModule {}The @Module decorator takes an object with metadata properties.
imports is for other modules you want to use inside this module.
Examples
This module groups a controller and a service related to cats.
NestJS
@Module({
controllers: [CatsController],
providers: [CatsService]
})
export class CatsModule {}This module imports another module, defines controllers and providers, and exports a service for use in other modules.
NestJS
@Module({
imports: [DatabaseModule],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService]
})
export class UsersModule {}Sample Program
This example shows a simple CatsModule with a controller and a service. The controller uses the service to return a list of cats when you visit the '/cats' route.
NestJS
import { Module } from '@nestjs/common'; import { CatsController } from './cats.controller'; import { CatsService } from './cats.service'; @Module({ controllers: [CatsController], providers: [CatsService] }) export class CatsModule {} // cats.controller.ts import { Controller, Get } from '@nestjs/common'; import { CatsService } from './cats.service'; @Controller('cats') export class CatsController { constructor(private readonly catsService: CatsService) {} @Get() findAll() { return this.catsService.findAll(); } } // cats.service.ts import { Injectable } from '@nestjs/common'; @Injectable() export class CatsService { private readonly cats = ['Tom', 'Garfield', 'Felix']; findAll() { return this.cats; } }
OutputSuccess
Important Notes
Always list controllers and providers inside the @Module decorator to make them part of the module.
Use exports to share providers with other modules.
Modules help keep your app organized like folders in a filing cabinet.
Summary
@Module groups related parts of your app together.
It uses metadata like imports, controllers, providers, and exports.
This helps NestJS know how to build and connect your app pieces.