ABOUT ME

Today
Yesterday
Total
  • Controllers
    Node.js/Nest 2023. 8. 23. 18:18

    Nest.js의 Controllers에 대해 정리하였습니다.


    < Controllers  >

    Controllers are responsible for handling incoming requests and returning responses to the client.

     

     

    •  A controller's purpose is to receive specific requests for the application. The routing mechanism controls which controller receives which requests. Frequently, each controller has more than one route, and different routes can perform different actions.
    • In order to create a basic controller, we use classes and decorators. Decorators associate classes with required metadata and enable Nest to create a routing map (tie requests to the corresponding controllers).

     

    Ex)

    import { Controller, Get } from '@nestjs/common';
    
    @Controller('cats')
    export class CatsController {}

    @Controller is a decorator, which is required to define a basic controller.

     

    < HINT >
    To create a controller using the CLI, simply execute the 
    $ nest g controller [name] command.​

     

     


    < Routing  >

    Using a path prefix in a @Controller() decorator allows us to easily group a set of related routes, and minimize repetitive code.

     

     

    Ex)

    import { Controller, Get } from '@nestjs/common';
    
    @Controller('cats')
    export class CatsController {
      @Get()
      findAll(): string {
        return 'This action returns all cats';
      }
    }

     

    The @Get() HTTP request method decorator before the findAll() method tells Nest to create a handler for a specific endpoint for HTTP requests. The endpoint corresponds to the HTTP request method (GET in this case) and the route path ( '/' in this case).

     

     


    < Manipulating Responses >

    Nest employs two different options for manipulating responses:

     

     

    < Standard(recommended) >
    Using this built-in method, when a request handler returns a JavaScript object or array, it will automatically be serialized to JSON. When it returns a JavaScript primitive type (e.g., stringnumberboolean), however, Nest will send just the value without attempting to serialize it. This makes response handling simple: just return the value, and Nest takes care of the rest.

    Furthermore, the response's status code is always 200 by default, except for POST requests which use 201. We can easily change this behavior by adding the @HttpCode(...) decorator at a handler-level (see Status codes).
    Library-specific >
    We can use the library-specific (e.g., Express) response object, which can be injected using the @Res( ) decorator in the method handler signature (e.g., findAll(@Res( ) response)).
    With this approach, you have the ability to use the native response handling methods exposed by that object. For example, with Express, you can construct responses using code like 
    response.status(200).send().

     

     


    < Request objects >

    Handlers often need access to the client request details. Nest provides access to the request object of the underlying platform (Express by default).

    We can access the request object by instructing Nest to inject it by adding the 
    @Req( ) decorator to the handler's signature.

     

    import { Controller, Get, Req } from '@nestjs/common';
    import { Request } from 'express';
    
    @Controller('cats')
    export class CatsController {
      @Get()
      findAll(@Req() request: Request): string {
        return 'This action returns all cats';
      }
    }

     

     

    +. Below is a list of the provided decorators and the plain platform-specific objects they represent.

    @Request(), @Req() req
    @Response(), @Res() res
    @Next() next
    @Session() req.session
    @Param(key?: string) req.params / req.params[key]
    @Body(key?: string) req.body / req.body[key]
    @Query(key?: string) req.query / req.query[key]
    @Headers(name?: string) req.headers / req.headers[name]
    @Ip() req.ip
    @HostParam() req.hosts

     

     


    < Request Payloads >

    DTO is an object that defines how the data will be sent over the network. We could determine the DTO schema by using TypeScript interfaces, or by simple classes.

     

    Ex)

    create-cat.dto.ts

    export class CreateCatDto {
      name: string;
      age: number;
      breed: string;
    }

     

    cats.controller.ts

    @Post()
    async create(@Body() createCatDto: CreateCatDto) {
      return 'This action adds a new cat';
    }

    : Our ValidationPipe can filter out properties that should not be received by the method handler.

     

     


    < Getting up and Running >

    Controllers always belong to a module, which is why we include the controllers array within the @Module() decorator. 

     

    Ex)

    import { Module } from '@nestjs/common';
    import { CatsController } from './cats/cats.controller';
    
    @Module({
      controllers: [CatsController],
    })
    export class AppModule {}

     

     


    Full Sample Source

    import { Controller, Get, Query, Post, Body, Put, Param, Delete } from '@nestjs/common';
    import { CreateCatDto, UpdateCatDto, ListAllEntities } from './dto';
    
    @Controller('cats')
    export class CatsController {
      @Post()
      create(@Body() createCatDto: CreateCatDto) {
        return 'This action adds a new cat';
      }
    
      @Get()
      findAll(@Query() query: ListAllEntities) {
        return `This action returns all cats (limit: ${query.limit} items)`;
      }
    
      @Get(':id')
      findOne(@Param('id') id: string) {
        return `This action returns a #${id} cat`;
      }
    
      @Put(':id')
      update(@Param('id') id: string, @Body() updateCatDto: UpdateCatDto) {
        return `This action updates a #${id} cat`;
      }
    
      @Delete(':id')
      remove(@Param('id') id: string) {
        return `This action removes a #${id} cat`;
      }
    }

     

     


    References : https://docs.nestjs.com/controllers

     

    'Node.js > Nest' 카테고리의 다른 글

    Exception Filters  (0) 2023.10.30
    Middlewares  (0) 2023.10.18
    Modules  (0) 2023.09.26
    Providers  (0) 2023.09.08
    Nest  (0) 2023.08.19

    댓글

Designed by Tistory.