pipe는 클라이언트 요청에서 들어오는 데이터를 유효성 검사 및 변환을 수행하여 서버가 원하는 데이터를 얻을 수 있도록 도와주는 클래스다.
pipes를 통하면 api의 해당 분기의 parameter를 지정할 수 있다.
Pipes를 적용하지 않은 경우
// cats/:id
@Get('/:id')
getOneCat(@Param() param) {
console.log(param); // ex) {id : '123'}
console.log(typeof param); // string
return 'one cat';
}
Pipes를 적용한 경우
// cats/:id
@Get('/:id')
getOneCat(@Param('id', ParseIntPipe) param: number) {
console.log(param); // ex) 123
console.log(typeof param); // number
return 'one cat';
}
id의 경우 일반적으로 숫자로 작성한다. 따라서 pipes를 적용해서 숫자가 나오게끔 해보자.
@Param('id', ParseIntPipe) param: number
를 통해 param의 id값을 가져오게 했으며,
param: number
로 지정해서 number 값이 나오게 했다.
positiveInt.pipe.ts
import { HttpException, Injectable, PipeTransform } from '@nestjs/common';
@Injectable()
export class PositiveIntPipe implements PipeTransform {
transform(value: number) {
console.log(value);
if (value < 0) {
throw new HttpException('value > 0 ', 400);
}
return value;
}
}