Validation

들어오는 요청에 대해 자동으로 유효성을 검증하기 위해, Nest 는 아래와 같은 몇 가지 파이프를 제공하고 있습니다.

- ValidationPipe

- ParseIntPipe

- ParseBoolPipe

- ParseArrayPipe

- ParseUUIDPipe

ValidationPipe 는 class-validator 패키지와 이 패키지가 제공하는 선언적 유효성 검증 데코레이터를 사용합니다.

ValidationPipe 는 모든 클라이언트 페이로드에 대한 유효성 검증 규칙 적용을 강제할 수 있는 편리한 접근 방식을 제공합니다.

내장 ValidationPipe 사용

요구되는 의존성 설치

$ npm i --save class-validator class-transformer

자동 유효성 검증

어플리케이션 레벨에서 ValidationPipe 을 바인딩하면 모든 엔드 포인트에 대해 부정확한 데이터가 들어오는 것으로부터 보호받을 수 있습니다.

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}

bootstrap();

파이프를 테스트해보기 위해, 예시를 통해 알아보자.

1. 테스트를 위한 컨트롤러 작성

@Post()
createUser(@Body() createUserDto: CreateUserDto) {
  return 'This controller creates a new user';
}

2. Dto 생성 및 Validation 규칙 추가

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

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

 

만약 유효하지 않은 email 프로퍼티 값을 가진 리퀘스트 바디와 함께 요청이 들어온다면, 어플리케이션은 자동적으로 아래의 리스폰스 바디와 함께 400 Bad Request 코드 응답을 보낼 것입니다.

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": ["email must be an email"]
}

 

ValidationPipe 는 리퀘스트 바디에 대한 유효섬 검증 외에 다른 리퀘스트 객체 프로퍼티에 대한 유효성 검증에 사용될 수 있습니다.

@Get(':id')
findUser(@Param() params: FineUserParams) {
  return 'This controller returns a user';
}

FindUserParams 는 class-validator 를 사용하여 유효성 검증 규칙을 정의하는 클래스입니다.

import { IsNumberString } from 'class-validator';

export class FindUserParams {
  @IsNumberString()
  id: number;
}

페이로드 객체 변환

네트워크를 통해 들어오는 페이로드는 자바스크립트 객체입니다. ValidationPipe 는 자동으로 DTO 클래스에 따라 객체 타이핑이 되도록 페이로드를 변환할 수 있습니다. 

자동 변환을 전역 레벨에서 활성화하기 위해 transform 속성 값을 true 로 설정합니다.

app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
  }),
);

자동 변환 옵션을 활성화하면 ValidationPipe 는 기본 자료형 변환을 수행하게 됩니다.

@Get(':id')
findUser(@Param('id') id: number) {
  console.log(typeof id === 'number'); // true
  return 'This controller returns a user';
}

기본적으로 모든 경로 파라미터와 쿼리 파라미터는 값이 string 으로 들어옵니다.

위 예시에서 id 타입을 number로 지정했기 때문에 ValidationPipe는 자동으로 string 식별자를 number 로 변환합니다.

명시적 변환

자동 변환 옵션이 비활성화되면 대안으로 ParseIntPipe, ParseBoolPipe 를 사용하여 값을 명시적으로 변환할 수 있습니다.

@Get(':id')
findUser(
  @Param('id', ParseIntPipe) id: number,
  @Query('sort', ParseBoolPipe) sort: boolean,
) {
  console.log(typeof id === 'number'); // true
  console.log(typeof sort === 'boolean'); // true
  return 'This controller returns a user';
}

 

출처

https://docs.nestjs.com/techniques/validation 

'라이브러리 & 프레임워크 > NestJS' 카테고리의 다른 글

[NestJS] Authentication  (0) 2022.11.29
Exception filter  (0) 2022.11.28
Mapped Types  (0) 2022.11.28
[TypeORM] 마이그레이션  (0) 2022.11.27
[TypeORM] TypeORM 엔티티 상속을 통한 중복 코드 제거  (0) 2022.11.26
복사했습니다!