! 읽기 전
이 시리즈에 있는 모든 글은 블로그 지향 기반 개발 & 공식 문서 기반으로 작성되었습니다 내용은 정확하지 않을 수도 있으며, 100% 신뢰하지 마시길 바랍니다
@Injectable()
데코레이터로 주석이 달린 클래스입니다. 파이프는 PipeTransform
인터페이스를 구현해야 합니다.인수
에서 작동import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
@Injectable()
export class ValidationPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
return value;
}
}
transform()
메소드를 제공해야함type | 인수가 body @Body(), query @Query(), param @Param() 또는 사용자 정의 매개 변수인지 여부를 나타냅니다 (여기에서 자세히 알아보십시오). |
---|---|
metatype | 인수의 메타 타입 (예: String)을 제공합니다. 참고: 라우트 핸들러 메소드 서명에서 유형 선언을 생략하거나 바닐라 JavaScript를 사용하는 경우 값은 undefined입니다. |
data | 문자열이 데코레이터에 전달되었습니다 (예: @Body('string')). 데코레이터 괄호를 비워두면 정의되지 않습니다(undefined). |
적용(controller.ts)
@Post()
@UsePipes(new ValidationPipe({ transform: true }))
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
@Injectable()
export class ParseIntPipe implements PipeTransform<string, number> {
transform(value: string, metadata: ArgumentMetadata): number {
const val = parseInt(value, 10);
if (isNaN(val)) {
throw new BadRequestException('Validation failed');
}
return val;
}
}
사용 방법 (service.ts)
async findOne(@Param('id', new ParseIntPipe()) id) {
return await this.catsService.findOne(id);
}
@Get(':id')
async findOne(@Param('id', new ParseUUIDPipe()) id) {
return await this.catsService.findOne(id);
}