본문 바로가기

node.js

Nest.js - pipes

파이프

파이프는 인터페이스 @Injectable()를 구현하는 데코레이터로 주석이 달린 클래스 입니다.

 

파이프에는 두 가지 일반적인 사용 사례가 있습니다.

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

 

  @Get(':id')
  getOneCat(@Param('id', ParseIntPipe, PositiveIntPipe) param: number) {
    console.log(param);
    // console.log(typeof param);
    return 'get one cat api';
  }

id로 받아오는 param은 string이다. 근데 보통 id는 number(숫자형)으로 많이 사용 되고   parseIntPipe를 통해 number 형으로 타입을 바꿔준다.   또한 number형이 아닌 다른 형태에 타입이 들어오게되면

 

아래와 같이 유효성 검사 까지 해준다.

import { Injectable, PipeTransform, HttpException } from '@nestjs/common';

@Injectable()
export class PositiveIntPipe implements PipeTransform {
  transform(value: number) {
    if (value < 0) {
      throw new HttpException('value > 0', 400);
    }
    return value;
  }
}

이처럼 custom하여 사용할 수도 있다.

 

getOneCat(@Param('id', ParseIntPipe, PositiveIntPipe) param: number)  에서 위에 보이는 사진 pipes and filters 패턴에

 

따라 ParseintPipe(Task A) ,PositiveIntPipe(Task B) 순서로 순차적으로 실행된다.

'node.js' 카테고리의 다른 글

Nest.Js - mongoDB 연결  (0) 2022.08.29
Nest.js - 인터셉터  (0) 2022.08.20
Nest.js - 예외 필터  (0) 2022.08.20
Nest.js - 미들웨어  (0) 2022.08.20
Nest.js - 모듈  (0) 2022.08.20