본문 바로가기

dev/nestjs

pipe

클라이언트가 보내는 값의 유효성 검사를 하기 위해 pipe 를 사용한다.

 

클라이언트쪽에서 필터로 한번 값을 걸러내고, nestjs 에서 pipe 를 통해 걸러내는 작업을 하는 사진이다.

 

 

 

커스텀 파이프와 빌트인 파이프가 있는데 그 중 빌트인 파이프로는 이렇게 있다.

 

Built-in pipes

Nest comes with nine pipes available out-of-the-box:

  • ValidationPipe
  • ParseIntPipe
  • ParseFloatPipe
  • ParseBoolPipe
  • ParseArrayPipe
  • ParseUUIDPipe
  • ParseEnumPipe
  • DefaultValuePipe
  • ParseFilePipe

 

 

컨트롤러에서 받는 값의 두번째 인자로 파이프를 넣어준다.

 

import { Controller, Get, Param, ParseIntPipe, Query, UsePipes } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(
    @Query('num', ParseIntPipe) num: number
  ): string {
    console.log(num);
    return this.appService.getHello();
  }
}

 

쿼리스트링으로 보내는 num값이 숫자가 아니면 validation failed를 뱉어낸다.

 

 

 

DTO의 유효성도 검사할 수 있다.

class-validator class-transformer 를 설치해준다.

--save : package.json의 dependency 항목에 모듈을 추가한다는 것

 

npm i class-validator class-transformer --save

 

 

Dto를 하나 만들어주고 @IsNotEmpty() 데코레이터를 달아준다.

 

import { IsNotEmpty } from "class-validator";

export class TestDto {
  @IsNotEmpty()
  name: string;
}

 

 

컨트롤러에서 @UserPipes(ValidationPipe) 를 달아주고 body 값을 받아주자

 

import { Body, Controller, Get, Param, ParseIntPipe, Post, Query, UsePipes, ValidationPipe } from '@nestjs/common';
import { AppService } from './app.service';
import { TestDto } from './test-dts';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post()
  @UsePipes(ValidationPipe)
  getHello(
    @Body() body: TestDto
  ): string {
    console.log(body);
    return this.appService.getHello();
  }
}

 

만약 name 이 비어있으면 오류가 나온다.

 

'dev > nestjs' 카테고리의 다른 글

프로바이더  (0) 2023.02.08
모듈  (0) 2023.02.08
미들웨어  (0) 2023.02.07
ejs  (0) 2023.02.04
컨트롤러  (1) 2023.02.03