12-Pipe
1. Pipe 소개 & ParseIntPipe

RequestMiddleware- Global Middleware
- Module Middleware
Guard- Global Guards
- Controller Guards
- Route Guards
Interceptors- Global Interceptors
- Controller Interceptors
- Route Interceptors
Pipes- Global Pipes
- Controller Pipes
- Route Pipes
- Route Parameter Pipes
ControllerServiceInterceptor- Router Interceptor
- Controller Interceptor
- Global Interceptor
Exception Filters- Route
- Controller
- Global
Response
1.1 Pipe란?
- Pipe란?
@injectable데코레이터된 클래스다.PipeTransform인터페이스를 상속(implements)받는다.- cf. https://docs.nestjs.com/pipes
- 파이프는 Controller에 제공되는 argument들에 적용된다.
- 이 argument에는
@Body, @Param등 이미 사용하고 있는 입력받는 Annotation들이 모두 포함된다. - Pipe는 argument 데이터를 가공한 후 Controller 메서드로 값들을 넘겨준다
- 이 argument에는
파이프는 2가지 사용 사례가 있다.
transformation(변형): 입력 데이터를 원하는 형식으로 변환(e.g. 문자열에서 정수로)validation(검증): 입력 데이터를 평가하고 유효한 경우, 변경하지 않고 그대로 전달한다.- 그렇지 않으면 예외를 throw한다.
1.2 Global Pipe
typescript
1import { ValidationPipe } from '@nestjs/common'2import { NestFactory } from '@nestjs/core'3import { AppModule } from './app.module'45async function bootstrap() {6const app = await NestFactory.create(AppModule)7app.useGlobalPipes(new ValidationPipe())8await app.listen(3000)9}10bootstrap()
1.3 Controller Pipe
typescript
1@Controller('movie')2@UsePipes(new ValidationPipe())3export class MovieController {4constructor(private readonly movieService: MovieService) {}56@Get()7getMovies(@Query('title') title?: string) {8return this.movieService.findAll(title)9}10}
1.4 Route Pipe
typescript
1@Controller('movie')2export class MovieController {3constructor(private readonly movieService: MovieService) {}45@Patch(':id')6@UsePipes(new ValidationPipe())7patchMovie(@Param('id') id: string, @Body() body: UpdateMovieDto) {8return this.movieService.update(+id, body)9}10}
1.5 Route Parameter Pipe
typescript
1@Controller('movie')2export class MovieController {3constructor(private readonly movieService: MovieService) {}45@Patch(':id')6patchMovie(@Param('id', ParseIntPipe) id: number, @Body() body: UpdateMovieDto) {7return this.movieService.update(id, body)8}9}
1.6 기본 Pipe 타입
ValidationPipe: 모든 Validation Annotation이 적용되도록 해준다ParseIntPipe: Int 값으로 변환, 검증한다ParseFloatPipe: Float 값으로 변환, 검증한다ParseBoolPipe: Bool 값으로 변환, 검증한다.ParseArrayPipe: Array 값으로 변환, 검증한다ParseUUIDPipe: UUID 값으로 변환, 검증한다ParseEnumPipe: Enum 값으로 변환, 검증한다.DefaultValuePipe: 기본값을 설정한다ParseFilePipe: 파일을 검증한다
위 파이프들은 @nestjs/common 패키지에서 호출 가능하다.
어떤 데코레이터이든, 2번째 파라미터에다가 검증하고 싶은 형태를 넣으면 된다.
posts.controller.ts
1// posts.controller.ts 생략2/*** 2) GET /posts/:id3* id에 해당하는 post를 가져온다4* e.g. 11이라는 ID를 갖고있는 Post 하나를 가져온다.5*/6// @Param('id') 뜻 : 가져오는 파라미터의 이름은 id이다7@Get(':id')8getPost(@Param('id', ParseIntPipe) id: number) {9return this.postsService.getPostById(id)10}1112// 생략1314/*** 4) PATCH /posts/:id15* id에 해당하는 post를 부분 변경한다16*/17@Patch(':id')18putPost(19@Param('id', ParseIntPipe) id: number, //20@Body('title') title?: string,21@Body('content') content?: string,22) {23return this.postsService.updatePost(id, title, content)24}2526/*** 5) DELETE /posts/:id27* id에 해당하는 post를 삭제한다28*/29@Delete(':id')30deletePost(@Param('id', ParseIntPipe) id: number) {31return this.postsService.deletePost(id)32}
기존에 id를 문자열로 받아, 숫자로 변환하기 위해 +를 붙인 걸 위와 같이 수정할 수 있다. 그리고 에러도 Pipe가 자동으로 던져준다.
1.7 Custom Pipe
typescript
1import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'23@Injectable()4export class ParseIntPipe implements PipeTransform<string, number> {5transform(value: string, metadata: ArgumentMetadata): number {6const val = parseInt(value, 10)7if (isNaN(val)) {8throw new BadRequestException('Validation failed. "${value}" is not a valid number.')9}10return val11}12}
2. custom Pipe 만들기
비밀번호가 8자리 이하여야만 한다고 가정한다면?
- 8자리 초과되면, 에러나게 만들기 위해, 커스텀 pipe 만들어보자
src/auth/pipe/password.pipe.ts파일을 만든다.- 커스텀 파이프를 만들기 위해 import 하는 건 그냥 외우면 된다.
password.pipe.ts
1import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common'23@Injectable()4export class PasswordPipe implements PipeTransform {5transform(value: any, metadata: ArgumentMetadata) {6if (value.toString().length > 8) {7throw new BadRequestException('비밀번호는 8자 이하로 입력해주세요!')8}9return value.toString()10}11}
그리고 만든 커스텀 Pipe를 쓰려고 하는 곳(auth 컨트롤러)에 파이프 쓰는 것처럼 쓰면 된다.
auth.controller.ts
1// auth.controller.ts 생략2@Post('register/email')3postRegisterEmail(4@Body('nickname') nickname: string, //5@Body('email') email: string,6@Body('password', PasswordPipe) password: string,7) {8return this.authService.registerWithEmail({9nickname,10email,11password,12})13}
3. DefaultValuePipe 사용
posts.controller.ts
1// posts.controller.ts 생략2/*** 3) POST /posts3* post를 생성한다4*/5@Post()6postPosts(7@Body('authorId') authorId: number, //8@Body('title') title: string,9@Body('content') content: string,10// 기본값을 true로 설정하는 파이프11@Body('isPublic', new DefaultValuePipe(true)) isPublic: boolean,12) {13return this.postsService.createPost(authorId, title, content)14}
new로 인스턴스화를 해주면, 해당 함수가 실행될 때마다 DefaultValuePipe가 새로 생성된다. 다른 Pipe에서도 new 인스턴스화를 해줄 수도 있다.
4. 여러 개의 파이프 동시에 사용
바로 위에서 DefaultValuePipe에서 테스트용으로 확인한 isPublic은 지워주거나 주석처리한다.
password.pipe.ts에 최소, 최대길이 커스텀 파이프를 만든다.
password.pipe.ts
1import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common'23@Injectable()4export class PasswordPipe implements PipeTransform {5transform(value: any, metadata: ArgumentMetadata) {6if (value.toString().length > 8) {7throw new BadRequestException('비밀번호는 8자 이하로 입력해주세요!')8}9return value.toString()10}11}1213@Injectable()14export class MaxLengthPipe implements PipeTransform {15constructor(private readonly length: number, private readonly subject: string) {}1617transform(value: any, metadata: ArgumentMetadata) {18if (value.toString().length > this.length) {19throw new BadRequestException(`${this.subject}의 최대 길이는 ${this.length}입니다.`)20}21return value.toString()22}23}2425@Injectable()26export class MinLengthPipe implements PipeTransform {27constructor(private readonly length: number) {}2829transform(value: any, metadata: ArgumentMetadata) {30if (value.toString().length < this.length) {31throw new BadRequestException(`최소 길이는 ${this.length}입니다.`)32}33return value.toString()34}35}
인스턴스화를 해서 넣게 되면, constructor값을 넣어줄 수가 있는 장점이 있다.
auth.controller.ts
1@Post('register/email')2postRegisterEmail(3@Body('nickname') nickname: string, //4@Body('email') email: string,5@Body('password', new MaxLengthPipe(8, '비밀번호'), new MinLengthPipe(3)) password: string,6) {7return this.authService.registerWithEmail({8nickname,9email,10password,11})12}
여러 개의 파이프를 넣고 싶으면, 2번째 파라미터부터 계속 넣으면, 계속 연달아서 파이프가 적용된다.