Requests in, results out
A controller is a class of route handlers. Decorators say which URL each method answers and which parts of the request it needs — so the method itself stays small and readable.
Route and parameter decorators
import { Body, Controller, Get, HttpCode, Param, Post, Query } from "@nestjs/common";
@Controller("dishes")
export class DishesController {
private dishes = [{ id: 1, name: "Momo", price: 180 }];
@Get()
findAll(@Query("max") max?: string) {
return max ? this.dishes.filter((d) => d.price <= Number(max)) : this.dishes;
}
@Get(":id")
findOne(@Param("id") id: string) {
return this.dishes.find((d) => d.id === Number(id)) ?? { error: "not found" };
}
@Post()
@HttpCode(201)
create(@Body() body: { name: string; price: number }) {
const dish = { id: this.dishes.length + 1, ...body };
this.dishes.push(dish);
return dish;
}
}- Also: @Put, @Patch, @Delete, @Headers("x-key"), and @Req() / @Res() for the raw objects (rarely needed).
- Generate files with the CLI: nest generate controller dishes.