
@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;
}
}