728x90

data transfer object 의 유효성 검사

class validator 를 사용하여 각 필드의 유효성 검사를 합니다.
pipe line에 쓰일 class-transformer도 설치합니다.

npm i class-validator
npm i class-transformer

create-restaurant.dto.ts

import { InputType, Field, ArgsType } from '@nestjs/graphql';
import { IsBoolean, IsString, Length } from 'class-validator';

@ArgsType()
export class CreateRestaurantDto {
  @Field((type) => String)
  @IsString()
  @Length(5, 10)
  name: string;
  @Field((type) => Boolean)
  @IsBoolean()
  isVegan: boolean;
  @Field((type) => String)
  @IsString()
  address: string;
  @Field((type) => String)
  @IsString()
  ownerName: string;
}

class validator 의 장점은 검사하고싶은 타입을 데코레이터로 쌓아 올리면 됩니다.

저의 문제였는지는 모르겠지만?!

class validator 안의 같은 이름의 데코레이터가 2개씩 있는 아이들이 있었습니다.

매개변수가 Options 아닌 IsString() 같은 경우는 매개변수 값이 없으면 서버에러를 불러오기 떄문에 처음에 당황하실수도 있어요

이렇게 설정 만 한다고 validation 이 되지는 않습니다.
파이프라인을 구축해줘야 하는데요

main.ts

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

app.useGlobalPipes(new ValidationPipe());

이 한줄을 추가해주셔야 타입 검사를 실행합니다.

http://localhost:3000/graphql

name 의 길이를 5 ~ 10 으로 설정한뒤 name 값을 2글자만 줘보았더니
message 로 최소 5글자 이상이여야 한다고 하네요
요기까지 Nestjs 에서 class validator 의 사용법이였습니다.

github 참고

728x90

'Side > uber-eats' 카테고리의 다른 글

Nestjs - Typeorm Repository 사용하기  (0) 2021.05.31
TypeORM setup 과 Nestjs Config  (0) 2021.05.23
Nestjs - InputTypes and ArgumentTypes  (0) 2021.05.22
NestJs - Arguments  (0) 2021.05.22
Nestjs - ObjectType  (0) 2021.05.22