CodePark/ questions / Controllers & routing
START PRACTICINGPRACTICE
Backend question · NestJS › Controllers & routing

What is the job of a controller in Nest, and how do you read the route param, query string and body in a handler?

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

  @Get(":id")
  findOne(@Param("id") id: string, @Query("expand") expand?: string) {
    return this.cats.findOne(id, expand);
  }

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

A controller receives incoming requests for a route prefix and returns responses. It should stay thin:

  • read the input
  • pass the work to a service
  • return the result

@Controller("cats") sets the prefix. Method decorators like @Get(), @Post(), @Put(), @Patch() and @Delete() connect HTTP methods and sub-paths to handlers.

Parameter decorators take data from the request:

  • @Param("id") for route params
  • @Query() for the query string
  • @Body() for the parsed body
  • also @Headers(), @Ip() and @Req()

When a handler returns a value, Nest sends it as the response automatically:

  • Objects and arrays become JSON.
  • Primitives (strings, numbers) are sent as they are.
  • Promises are awaited first.
  • Controllers handle routing and stay thin, passing the work to services.
  • @Controller() sets the prefix, and method decorators set the routes.
  • @Param, @Query, @Body and @Headers read data from the request.
  • Nest serialises return values automatically and awaits promises.