Sikau

NestJS · Day 2 · about 30 min

Controllers in depth

Prefixes, params, query, body and status codes.

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.

The rest of this lesson

  • Params are strings until you say otherwiseexplain
  • Designing resource routesexplain
  • Which URL?predict
  • Complete the controllerfill
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of NestJS