NestJS 파이프(Pipe)란?
파이프는 NestJS에서 입력 데이터를 가공하거나 검증하는 역할을 하는 클래스이다. 컨트롤러가 핸들러를 실행하기 전에 파이프가 먼저 데이터를 처리하며, 변환(transform)과 검증(validate)이라는 두 가지 주요 기능을 제공한다.
주요 기능
1. 변환 (Transformation)
요청에서 받은 데이터를 원하는 형식으로 변환한다. 예: 문자열 → 숫자.
예시 코드:
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return `Item #${id}`;
}
위와 같이 사용하면 URL 파라미터가 string이라도 ParseIntPipe를 통해 number로 변환되어 처리된다.
2. 검증 (Validation)
데이터가 유효한지 확인하고, 유효하지 않으면 예외를 던진다.
예시: class-validator를 활용한 DTO 검증
export class CreateUserDto {
@IsString()
name: string;
@IsInt()
age: number;
}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return createUserDto;
}
파이프 적용 위치
핸들러 레벨: 특정 메서드의 파라미터에만 적용
컨트롤러 레벨: 컨트롤러 전체에 적용
전역 레벨: 애플리케이션 전체에 적용 (main.ts)
전역 설정 예시:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
ValidationPipe 기본값
new ValidationPipe({
whitelist: false, // DTO에 정의되지 않은 속성을 자동 제거하지 않음
forbidNonWhitelisted: false, // 정의되지 않은 속성이 있어도 에러 발생 X
transform: false, // DTO 타입 자동 변환 X
disableErrorMessages: false, // 상세 에러 메시지를 활성화 (true이면 메시지 숨김)
validationError: {
target: true, // 유효성 검사 실패 시 입력 객체 포함
value: true, // 유효성 검사 실패 시 입력된 값 포함
},
stopAtFirstError: false, // 여러 개의 오류가 있어도 모든 오류 반환
});
===>ValidationPipe 프로젝트 설정
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { CustomExceptionFilter } from '../common/custom-exception.filter';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new CustomExceptionFilter());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // ❌ DTO에 정의되지 않은 속성은 자동 제거
forbidNonWhitelisted: true, // ???? 정의되지 않은 속성이 있으면 400 에러 발생
transform: true, // ???? DTO의 타입을 자동 변환 (예: "1" -> 1)
}),
);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap().catch((err) => {
console.error('Bootstrap error:', err);
process.exit(1);
});
커스텀 파이프 만들기
사용자 정의 로직으로 파이프를 만들 수 있다. 예를 들어, 문자열을 무조건 대문자로 바꾸는 파이프:
@Injectable()
export class UppercasePipe implements PipeTransform {
transform(value: any) {
if (typeof value !== 'string') {
throw new BadRequestException('Validation failed: not a string');
}
return value.toUpperCase();
}
}
사용 예:
@Get()
greet(@Query('name', UppercasePipe) name: string) {
return `Hello, ${name}`;
}
✅ 요약
파이프는 데이터 변환 및 유효성 검사를 수행하는 강력한 도구
내장 파이프와 커스텀 파이프 모두 유연하게 사용 가능
전역/컨트롤러/핸들러 레벨에 따라 다양하게 설정 가능
ValidationPipe + DTO 조합은 가장 일반적인 검증 방식
// NestJS Pipe(파이프)란?
// NestJS에서 파이프는 요청 데이터를 변환하거나 검증하는 데 사용됩니다.
// 기본 제공 파이프와 커스텀 파이프를 활용하여 요청을 처리할 수 있습니다.
import { Controller, Get, Query, ParseIntPipe, UsePipes, ValidationPipe } from '@nestjs/common';
import { IsInt, IsOptional, IsString } from 'class-validator';
// DTO (Data Transfer Object) 정의
// ValidationPipe를 활용한 데이터 유효성 검사
class SampleDto {
@IsString()
name: string;
@IsOptional()
@IsInt()
age?: number;
}
@Controller('sample')
export class SampleController {
// 1. 기본 제공되는 ParseIntPipe 사용
// - ?id=123 을 정수로 변환하여 처리
@Get('id')
getById(@Query('id', ParseIntPipe) id: number) {
return `ID: ${id}`;
}
// 2. ValidationPipe를 사용한 DTO 검증
// - ?name=John&age=30 요청 시 DTO에 맞게 변환 및 유효성 검사
@Get('validate')
@UsePipes(new ValidationPipe({ transform: true }))
validateDto(@Query() query: SampleDto) {
return `Validated Name: ${query.name}, Age: ${query.age}`;
}
}
// 3. 커스텀 파이프 예제
// - 특정 데이터를 변환하거나 검증하는 역할 수행
import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common';
@Injectable()
export class CustomPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
if (typeof value !== 'string' || value.trim() === '') {
throw new BadRequestException('값이 유효하지 않습니다.');
}
return value.trim().toUpperCase(); // 데이터를 대문자로 변환하여 반환
}
}
// 4. 커스텀 파이프 사용 예제
@Controller('custom')
export class CustomController {
// - ?text=hello 요청 시 "HELLO" 로 변환하여 반환
@Get('uppercase')
useCustomPipe(@Query('text', new CustomPipe()) text: string) {
return `Processed Text: ${text}`;
}
}
/* 정리
1️⃣ **기본 제공 파이프**
- ParseIntPipe: 문자열을 숫자로 변환
- ValidationPipe: DTO 기반의 유효성 검사 수행
2️⃣ **커스텀 파이프**
- CustomPipe: 요청 데이터를 대문자로 변환
✅ 파이프를 활용하면 NestJS에서 요청 데이터를 안전하게 처리하고 변환할 수 있습니다! */














댓글 ( 0)
댓글 남기기