Pipe 란
Pipe 는 @Injectable() decorator 가 달린 class 이다.
이는 PipeTransform interface 로 구현되어 있다.
Pipe 의 두 가지 종류
- transformation: 입력 데이터를 원하는 데이터 타입으로 변환한다.
- validation: 입력 데이터가 유효한지 평가한다.(ex. null, undefined ...)
예제
- 내가 사용해볼 예제는 다음과 같다.
@Get('/:id') getBoardById(@Param('id', new ParseIntPipe({ errorHttpStatusCode: HttpStatus.FORBIDDEN })) id: string): Board { return this.boardsService.getBoardById(id); }
- pipe 에 class 자체를 넣으면 ParseIntPipe의 기본적인 조건으로 statusCode 와 Message 가 나오는데 이처럼 객체로 던지면 ParseIntPipe transformer 를 던지면 이에 에러가 생겼을 때 커스텀 된 메시지와 상태코드를 응답할 수 있다.
- 이때는 에러 코드로 HttpStatus 의 Forbindden 을 ParseIntPipe 의 생성자 인자에 넘겼는데 'localhost:8080/boards/aaa' 와 같이 가장 끝 값이 숫자가 아닌 값을 넘겼을 때 다음과 같은 에러로 응답이 왔다.
{"message":"Validation failed (numeric string is expected)","error":"Forbidden","statusCode":403}
- 이때 handdler 의 인자에 있는 @Param 데코레이터의 인자로 특정 pipe 생성자를 통해 생성된 인스턴스를 넘기지 않고, class 자체를 넘기면 커스텀 되지 않은 기본값이 응답 온다.
{"message":"Validation failed (numeric string is expected)","error":"Bad Request","statusCode":400}
```
참고
Pipe 란
Pipe 는 @Injectable() decorator 가 달린 class 이다.
이는 PipeTransform interface 로 구현되어 있다.
Pipe 의 두 가지 종류
- transformation: 입력 데이터를 원하는 데이터 타입으로 변환한다.
- validation: 입력 데이터가 유효한지 평가한다.(ex. null, undefined ...)
예제
- 내가 사용해볼 예제는 다음과 같다.
@Get('/:id') getBoardById(@Param('id', new ParseIntPipe({ errorHttpStatusCode: HttpStatus.FORBIDDEN })) id: string): Board { return this.boardsService.getBoardById(id); }
- pipe 에 class 자체를 넣으면 ParseIntPipe의 기본적인 조건으로 statusCode 와 Message 가 나오는데 이처럼 객체로 던지면 ParseIntPipe transformer 를 던지면 이에 에러가 생겼을 때 커스텀 된 메시지와 상태코드를 응답할 수 있다.
- 이때는 에러 코드로 HttpStatus 의 Forbindden 을 ParseIntPipe 의 생성자 인자에 넘겼는데 'localhost:8080/boards/aaa' 와 같이 가장 끝 값이 숫자가 아닌 값을 넘겼을 때 다음과 같은 에러로 응답이 왔다.
{"message":"Validation failed (numeric string is expected)","error":"Forbidden","statusCode":403}
- 이때 handdler 의 인자에 있는 @Param 데코레이터의 인자로 특정 pipe 생성자를 통해 생성된 인스턴스를 넘기지 않고, class 자체를 넘기면 커스텀 되지 않은 기본값이 응답 온다.
{"message":"Validation failed (numeric string is expected)","error":"Bad Request","statusCode":400}
```