코딩일상

[nest.js] Pipes란?? Pipes 예제 본문

개발 공부/nest.js

[nest.js] Pipes란?? Pipes 예제

solutionMan 2022. 12. 5. 16:42
반응형

 

Pipes란??

파이프는 클라이언트 요청에서 들어오는 데이터를 유효성 검사 및 변환을 수행하여 서버가 원하는 데이터를 얻을수 있도록 도와주는 클래스이다.

 

파이프는 단방향 통신을 위한 용도로 사용됩니다.

하나의 파이프는 이전 파이프에서 전달된 결과를 입력 값으로 받아 또 다른 결과 값을 내놓습니다.

NestJS에서의 파이프는 클라이언트 요청에서 들어오는 데이터를 유효성 검사 및 변환을 수행하여 서버가 원하는 데이터를 얻을 수 있도록 도와주는 역할을 합니다

 

  • 변환 : 입력 데이터를 원하는 형식으로 변환(예: 문자열에서 정수로)
  • validation : 입력 데이터를 평가하고 유효한 경우 변경되지 않은 상태로 전달합니다. 그렇지 않으면 데이터가 올바르지 않을 때 예외를 throw합니다

 

왜 이름이 Pipes인가??

비즈니스 로직을 실행하기전,

들어온 데이터에 대해 가공과정들일 순서대로 일어나는 과정이 Pipe같이 이루어지기에 

 

Pipes and Filters pattern - Azure Architecture Center

Break down a task that performs complex processing into a series of separate elements that can be reused.

learn.microsoft.com

Pipes적용 예시

http://localhost:8000/cats/123  이와 같이 요청을 보낼경우

//cats.controllers.ts
  

  @Get(':id')
  getOnecat(@Param('id') param) {
    console.log(param);
    console.log(typeof param);
    return 'get one cat api';
  }

param의 결과가값과 타입을 알 수있다.

 

하지만 일반적으로 이예제에서 사용되는 id의 경우 Number타입으로 사용이 많이 되기에,

Built-In NestJS Pipes의  종류 중 ParseIntPipe를 이용하여 진행을 해보았다.

  //cats.controllers.ts
  
  @Get(':id')
  //ParseIntPipe으로 인해 string 타입을 Number타입으로 변환가능
  //더불어, 유효성검사 까지 가능 :id에 Number 타입이 아닌경우 에러 발생
  getOnecat(@Param('id', ParseIntPipe) id: number) {
    console.log(id);
    console.log(typeof id);
    return 'get one cat api';
  }

Param에 number 타입이 아니라 string타입이 들어오는 경우 validation 체크 또한 해주어 에러를 발생시키다.

 

 Pipes 종류(Built-In NestJS Pipes)

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

 

레퍼런스

 

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

 

 

Nestjs를 배워보자 6일차 - Pipe, 예외처리 (John ahn님 강의)

본 강의는 'john ahn'님의 강의를 정리한 내용입니다.https://www.youtube.com/watch?v=3JminDpCJNE파이프란 무엇인가? @Injectable()데코레이터로 주석이 달린 클래스이다. 또한, 파이프는 컨트롤러 경로 처리기에

velog.io

 

반응형
Comments