DevBoi

[NestJs] Custom Pipeline 만들어보기 본문

Develop/[NestJs]

[NestJs] Custom Pipeline 만들어보기

HiSmith 2023. 7. 2. 23:57
반응형

nestjs의 고유기능 pipeline에 대해서 살펴보자

아래와 같이 동작한다.

0.모듈 설치

npm install class-validator class-transformer --save

 

 

1. sample code

import { ArgumentMetadata, PipeTransform } from "@nestjs/common";

export class AuthValidationPipe implements PipeTransform{
    transform(value: any, metadata: ArgumentMetadata) {
        console.log(value);
        console.log(metadata);
        return value;
    }
}

 

2.특정 컨트롤러에서 만 해당 파이프라인이 적용되게 하기

 

2-1. 파라미터 레벨

  @Get(":id")
  testMethod(@Body('test',AuthValidationPipe) test: string){

  }

 

2-2. 핸들러 레벨

@UsePipes(AuthValidationPipe)
@ApiTags('corp') // (옵션) 태그 추가
@Controller('corp')
export class CorpController {
  constructor(private readonly corpService: CorpService) {}
  
  @ApiOperation({ summary: '업체 조회' }) // (옵션) API 동작 설명  
  @Get(':id')
  async findOne(@Param('id') id: number) : Promise<Corp>{
    const corp =  await this.corpService.findbyCorpId(id);
    if(!corp){    
      throw new NotFoundException();
    }
    return corp;
  }

 

2-4. 메소드 레벨

  @UsePipes(AuthValidationPipe)
  @Get("/test/:id")
  testMethod(@Body('test') test: string){

  }

2-5. 글로벌 레벨 (app.useGlobalPipes 참고)

async function bootstrap() {
  //http://127.0.0.1:3000
  const app = await NestFactory.create(AppModule);
  //app.useGlobalPipes(new ValidationPipe());
  const config = new DocumentBuilder()
    .setTitle('API Documentation')
    .setDescription('API Documentation for your application')
    .setVersion('1.0')
    .addTag('users') // (옵션) 태그 추가
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  app.useGlobalPipes(new AuthValidationPipe);

  await app.listen(3000);
}
bootstrap();

 

 

 

3. 사용 방법들

 

 3-1. 유효성 검증 (넘어온 값이 스미스,smith ? x -> exception)

export class AuthValidationPipe implements PipeTransform{
    readonly nameType =[
    '스미스',
    'smith'
    ];
    transform(value: any, metadata: ArgumentMetadata) {
        if(this.nameType.indexOf(value) == -1)
            throw new NotFoundException();
        return value;
    }
}

 

3-2. 바디나, 헤더에 메타타입을 확인 가능 (value외 메타데이터 확인)

 

 

대부분 유효성 검증을 위해 사용이 된다.

nestJs자동 제공해주는 파이프라인 때문에, 객체 바인딩도 알아서 되고 적용, 실행이알아서 된다.

(제공해주는 파이프라인에 대해서는 나중에 살펴보도록 하자)

 

dto에서 제공하는 벨리데이션은 별도로 아래와 같이 사용가능하기 때문에

별로, 파이프라인에서 막지 않는 방법을 선호하는 듯 하다.

import { IsEmail, IsNotEmpty } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsNotEmpty()
  password: string;
}

 

다음에는, 자동 제공 해주는 파이프라인과 벨리데이션 방법에 대해서 조금더 알아보는것이 좋을듯하다.

 

반응형