NestJS 11 cheatsheet

NestJS 11: Controllers, providers and modules

5 common NestJS 11 tasks.

Write a controller

Decorators map methods to routes. Pipes such as ParseIntPipe convert and validate parameters.

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

  @Get()
  findAll(@Query('limit') limit?: string) {
    return this.cats.findAll(limit ? +limit : undefined);
  }

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

  @Post()
  @HttpCode(201)
  create(@Body() dto: CreateCatDto) {
    return this.cats.create(dto);
  }
}

Write a provider (service)

@Injectable classes are created and injected by Nest. Throw built-in HTTP exceptions for errors.

@Injectable()
export class CatsService {
  private cats: Cat[] = [];

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

Wire things together in a module

A module declares its controllers and providers, and exports what other modules may use.

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

Provide a value or factory

Register a value, class or factory under a token, for example to inject configuration or fakes.

providers: [
  { provide: 'API_KEY', useValue: process.env.API_KEY },
  { provide: Logger, useClass: PinoLogger },
]

Load configuration

Make environment variables available everywhere, then inject ConfigService.

ConfigModule.forRoot({ isGlobal: true })

// in a service
constructor(private config: ConfigService) {}
const port = this.config.get<number>('PORT', 3000);

Was this page helpful?