Skip to Content
BackendNestJs12-Pipe

1. Pipe 소개 & ParseIntPipe

Pipe

  1. Request
  2. Middleware
    • Global Middleware
    • Module Middleware
  3. Guard
    • Global Guards
    • Controller Guards
    • Route Guards
  4. Interceptors
    • Global Interceptors
    • Controller Interceptors
    • Route Interceptors
  5. Pipes
    • Global Pipes
    • Controller Pipes
    • Route Pipes
    • Route Parameter Pipes
  6. Controller
  7. Service
  8. Interceptor
    • Router Interceptor
    • Controller Interceptor
    • Global Interceptor
  9. Exception Filters
    • Route
    • Controller
    • Global
  10. Response

1.1 Pipe란?

  • Pipe란? @injectable 데코레이터된 클래스다.
  • 파이프는 Controller에 제공되는 argument들에 적용된다.
    • 이 argument에는 @Body, @Param등 이미 사용하고 있는 입력받는 Annotation들이 모두 포함된다.
    • Pipe는 argument 데이터를 가공한 후 Controller 메서드로 값들을 넘겨준다

파이프는 2가지 사용 사례가 있다.

  • transformation(변형) : 입력 데이터를 원하는 형식으로 변환(e.g. 문자열에서 정수로)
  • validation(검증) : 입력 데이터를 평가하고 유효한 경우, 변경하지 않고 그대로 전달한다.
    • 그렇지 않으면 예외를 throw한다.

1.2 Global Pipe

typescript
1
import { ValidationPipe } from '@nestjs/common'
2
import { NestFactory } from '@nestjs/core'
3
import { AppModule } from './app.module'
4
5
async function bootstrap() {
6
const app = await NestFactory.create(AppModule)
7
app.useGlobalPipes(new ValidationPipe())
8
await app.listen(3000)
9
}
10
bootstrap()

1.3 Controller Pipe

typescript
1
@Controller('movie')
2
@UsePipes(new ValidationPipe())
3
export class MovieController {
4
constructor(private readonly movieService: MovieService) {}
5
6
@Get()
7
getMovies(@Query('title') title?: string) {
8
return this.movieService.findAll(title)
9
}
10
}

1.4 Route Pipe

typescript
1
@Controller('movie')
2
export class MovieController {
3
constructor(private readonly movieService: MovieService) {}
4
5
@Patch(':id')
6
@UsePipes(new ValidationPipe())
7
patchMovie(@Param('id') id: string, @Body() body: UpdateMovieDto) {
8
return this.movieService.update(+id, body)
9
}
10
}

1.5 Route Parameter Pipe

typescript
1
@Controller('movie')
2
export class MovieController {
3
constructor(private readonly movieService: MovieService) {}
4
5
@Patch(':id')
6
patchMovie(@Param('id', ParseIntPipe) id: number, @Body() body: UpdateMovieDto) {
7
return 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/:id
3
* id에 해당하는 post를 가져온다
4
* e.g. 11이라는 ID를 갖고있는 Post 하나를 가져온다.
5
*/
6
// @Param('id') 뜻 : 가져오는 파라미터의 이름은 id이다
7
@Get(':id')
8
getPost(@Param('id', ParseIntPipe) id: number) {
9
return this.postsService.getPostById(id)
10
}
11
12
// 생략
13
14
/*** 4) PATCH /posts/:id
15
* id에 해당하는 post를 부분 변경한다
16
*/
17
@Patch(':id')
18
putPost(
19
@Param('id', ParseIntPipe) id: number, //
20
@Body('title') title?: string,
21
@Body('content') content?: string,
22
) {
23
return this.postsService.updatePost(id, title, content)
24
}
25
26
/*** 5) DELETE /posts/:id
27
* id에 해당하는 post를 삭제한다
28
*/
29
@Delete(':id')
30
deletePost(@Param('id', ParseIntPipe) id: number) {
31
return this.postsService.deletePost(id)
32
}

기존에 id를 문자열로 받아, 숫자로 변환하기 위해 +를 붙인 걸 위와 같이 수정할 수 있다. 그리고 에러도 Pipe가 자동으로 던져준다.


1.7 Custom Pipe

typescript
1
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'
2
3
@Injectable()
4
export class ParseIntPipe implements PipeTransform<string, number> {
5
transform(value: string, metadata: ArgumentMetadata): number {
6
const val = parseInt(value, 10)
7
if (isNaN(val)) {
8
throw new BadRequestException('Validation failed. "${value}" is not a valid number.')
9
}
10
return val
11
}
12
}

2. custom Pipe 만들기

비밀번호가 8자리 이하여야만 한다고 가정한다면?

  • 8자리 초과되면, 에러나게 만들기 위해, 커스텀 pipe 만들어보자
  • src/auth/pipe/password.pipe.ts파일을 만든다.
  • 커스텀 파이프를 만들기 위해 import 하는 건 그냥 외우면 된다.
password.pipe.ts
1
import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common'
2
3
@Injectable()
4
export class PasswordPipe implements PipeTransform {
5
transform(value: any, metadata: ArgumentMetadata) {
6
if (value.toString().length > 8) {
7
throw new BadRequestException('비밀번호는 8자 이하로 입력해주세요!')
8
}
9
return value.toString()
10
}
11
}

그리고 만든 커스텀 Pipe를 쓰려고 하는 곳(auth 컨트롤러)에 파이프 쓰는 것처럼 쓰면 된다.

auth.controller.ts
1
// auth.controller.ts 생략
2
@Post('register/email')
3
postRegisterEmail(
4
@Body('nickname') nickname: string, //
5
@Body('email') email: string,
6
@Body('password', PasswordPipe) password: string,
7
) {
8
return this.authService.registerWithEmail({
9
nickname,
10
email,
11
password,
12
})
13
}

3. DefaultValuePipe 사용

posts.controller.ts
1
// posts.controller.ts 생략
2
/*** 3) POST /posts
3
* post를 생성한다
4
*/
5
@Post()
6
postPosts(
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
) {
13
return this.postsService.createPost(authorId, title, content)
14
}

new로 인스턴스화를 해주면, 해당 함수가 실행될 때마다 DefaultValuePipe가 새로 생성된다. 다른 Pipe에서도 new 인스턴스화를 해줄 수도 있다.


4. 여러 개의 파이프 동시에 사용

바로 위에서 DefaultValuePipe에서 테스트용으로 확인한 isPublic은 지워주거나 주석처리한다.

password.pipe.ts에 최소, 최대길이 커스텀 파이프를 만든다.

password.pipe.ts
1
import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common'
2
3
@Injectable()
4
export class PasswordPipe implements PipeTransform {
5
transform(value: any, metadata: ArgumentMetadata) {
6
if (value.toString().length > 8) {
7
throw new BadRequestException('비밀번호는 8자 이하로 입력해주세요!')
8
}
9
return value.toString()
10
}
11
}
12
13
@Injectable()
14
export class MaxLengthPipe implements PipeTransform {
15
constructor(private readonly length: number, private readonly subject: string) {}
16
17
transform(value: any, metadata: ArgumentMetadata) {
18
if (value.toString().length > this.length) {
19
throw new BadRequestException(`${this.subject}의 최대 길이는 ${this.length}입니다.`)
20
}
21
return value.toString()
22
}
23
}
24
25
@Injectable()
26
export class MinLengthPipe implements PipeTransform {
27
constructor(private readonly length: number) {}
28
29
transform(value: any, metadata: ArgumentMetadata) {
30
if (value.toString().length < this.length) {
31
throw new BadRequestException(`최소 길이는 ${this.length}입니다.`)
32
}
33
return value.toString()
34
}
35
}

인스턴스화를 해서 넣게 되면, constructor값을 넣어줄 수가 있는 장점이 있다.

auth.controller.ts
1
@Post('register/email')
2
postRegisterEmail(
3
@Body('nickname') nickname: string, //
4
@Body('email') email: string,
5
@Body('password', new MaxLengthPipe(8, '비밀번호'), new MinLengthPipe(3)) password: string,
6
) {
7
return this.authService.registerWithEmail({
8
nickname,
9
email,
10
password,
11
})
12
}

여러 개의 파이프를 넣고 싶으면, 2번째 파라미터부터 계속 넣으면, 계속 연달아서 파이프가 적용된다.