TExcelTAD
Home › Express & NestJS › Modules, Controllers & Providers

Modules, Controllers & Providers

A Nest application is built from three kinds of classes. Learn what each one is responsible for and the rest of the framework falls into place.

Building block Decorator Responsibility
Controller @Controller() receive HTTP requests, return responses — no business logic
Provider (usually a service) @Injectable() business logic, data access, anything reusable; injected where needed
Module @Module() groups related controllers and providers and decides what is shared

A feature module, file by file

The CLI generates the skeleton for you:

bash · try it yourself
nest generate resource cats --no-spec
? What transport layer do you use? REST API
? Would you like to generate CRUD entry points? Yes
CREATE src/cats/cats.controller.ts
CREATE src/cats/cats.module.ts
CREATE src/cats/cats.service.ts
CREATE src/cats/dto/create-cat.dto.ts
CREATE src/cats/dto/update-cat.dto.ts
CREATE src/cats/entities/cat.entity.ts
UPDATE src/app.module.ts

The provider

ts
// src/cats/cats.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';

export interface Cat { id: number; name: string; age: number }

@Injectable()
export class CatsService {
  private readonly cats: Cat[] = [{ id: 1, name: 'Mochi', age: 3 }];
  private nextId = 2;

  findAll(): Cat[] {
    return this.cats;
  }

  findOne(id: number): Cat {
    const cat = this.cats.find((c) => c.id === id);
    if (!cat) throw new NotFoundException(`Cat ${id} not found`);
    return cat;
  }

  create(data: Omit<Cat, 'id'>): Cat {
    const cat = { id: this.nextId++, ...data };
    this.cats.push(cat);
    return cat;
  }
}

@Injectable() marks the class as something Nest's container can create and inject. The service knows nothing about HTTP — except for throwing NotFoundException, which Nest turns into a 404.

The controller

ts
// src/cats/cats.controller.ts
import { Body, Controller, Get, HttpCode, Param, ParseIntPipe, Post, Query } from '@nestjs/common';
import { CatsService } from './cats.service';
import { CreateCatDto } from './dto/create-cat.dto';

@Controller('cats')                       // route prefix: /cats
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()                                  // GET /cats?minAge=2
  findAll(@Query('minAge') minAge?: string) {
    const all = this.catsService.findAll();
    return minAge ? all.filter((c) => c.age >= Number(minAge)) : all;
  }

  @Get(':id')                             // GET /cats/1
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.catsService.findOne(id);
  }

  @Post()                                 // POST /cats  (201 by default)
  create(@Body() dto: CreateCatDto) {
    return this.catsService.create(dto);
  }
}
Parameter decorator Express equivalent
@Param('id') req.params.id
@Query('minAge') req.query.minAge
@Body() req.body (JSON parsing is enabled by default)
@Headers('authorization') req.get('authorization')
@Req() / @Res() the raw Express req / res (avoid @Res() unless necessary)

Route method decorators: @Get, @Post, @Put, @Patch, @Delete, @All. @HttpCode(204) changes the default status (200, or 201 for @Post), and @Header('Cache-Control', 'no-store') sets a header.

The module

ts
// src/cats/cats.module.ts
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
  controllers: [CatsController],
  providers: [CatsService],
  exports: [CatsService],   // other modules that import CatsModule may inject CatsService
})
export class CatsModule {}

// src/app.module.ts
@Module({ imports: [CatsModule] })
export class AppModule {}

Calling it

bash · try it yourself
curl http://localhost:3000/cats
curl -X POST http://localhost:3000/cats -H "Content-Type: application/json" -d '{"name":"Pixel","age":1}'
curl "http://localhost:3000/cats?minAge=2"
curl http://localhost:3000/cats/9
curl http://localhost:3000/cats/abc
[{"id":1,"name":"Mochi","age":3}]
{"id":2,"name":"Pixel","age":1}
[{"id":1,"name":"Mochi","age":3}]
{"message":"Cat 9 not found","error":"Not Found","statusCode":404}
{"message":"Validation failed (numeric string is expected)","error":"Bad Request","statusCode":400}

Module encapsulation

Providers are private to their module unless exported. Another module can use CatsService only if it imports: [CatsModule] and CatsModule lists the service in exports. This playground models those two rules:

ts · try it yourself
type ModuleDef = { name: string; providers: string[]; exports?: string[]; imports?: ModuleDef[] };

function canInject(mod: ModuleDef, token: string): boolean {
  if (mod.providers.includes(token)) return true; // own providers
  return (mod.imports ?? []).some((imp) => (imp.exports ?? []).includes(token)); // exported by an import
}

const DatabaseModule: ModuleDef = { name: 'DatabaseModule', providers: ['DbPool', 'Migrator'], exports: ['DbPool'] };
const CatsModule: ModuleDef = { name: 'CatsModule', providers: ['CatsService'], exports: ['CatsService'], imports: [DatabaseModule] };
const OwnersModule: ModuleDef = { name: 'OwnersModule', providers: ['OwnersService'], imports: [CatsModule] };

const questions: [ModuleDef, string][] = [
  [CatsModule, 'CatsService'],
  [CatsModule, 'DbPool'],
  [CatsModule, 'Migrator'],
  [OwnersModule, 'CatsService'],
  [OwnersModule, 'DbPool'],
];
for (const [mod, token] of questions) {
  console.log(`${mod.name.padEnd(12)} inject ${token.padEnd(12)} ${canInject(mod, token) ? 'ok' : 'ERROR: not available'}`);
}
CatsModule   inject CatsService  ok
CatsModule   inject DbPool       ok
CatsModule   inject Migrator     ERROR: not available
OwnersModule inject CatsService  ok
OwnersModule inject DbPool       ERROR: not available

Imports are not transitive: OwnersModule imports CatsModule, which imports DatabaseModule, but OwnersModule still can't see DbPool. (A module can re-export an imported module by listing it in exports.) When the rule is broken, Nest refuses to start with an error like "Nest can't resolve dependencies of the OwnersService (?). Please make sure that the argument DbPool at index [0] is available in the OwnersModule context."

Special module kinds

Kind How Use
global module @Global() on the module config, logging — available everywhere without importing
dynamic module static forRoot(options) returning a module configurable libraries: ConfigModule.forRoot(), TypeOrmModule.forRoot({...})
shared module a module that only exports providers utilities used by many features

Tip: Keep controllers thin. If a controller method has more than a few lines, the logic probably belongs in a service — where it can be unit-tested and reused by other controllers, queues or CLI commands.

Test yourself

Which class should contain the business rule 'a cat's age can't be negative'?

  1. The controller
  2. A provider/service
  3. The module
  4. main.ts

Module B imports Module A. When can a provider in B inject A's MailService?

  1. Always
  2. Only if A lists MailService in its exports
  3. Only if MailService is a controller
  4. Never

Which decorator gives a controller method access to req.params.id?

  1. @Query('id')
  2. @Body('id')
  3. @Param('id')
  4. @Get('id')