Validation

2022. 11. 28. 16:43·라이브러리 & 프레임워크/NestJS

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
'라이브러리 & 프레임워크/NestJS' 카테고리의 다른 글
  • [NestJS] Authentication
  • Exception filter
  • Mapped Types
  • [TypeORM] 마이그레이션
rondeveloper
rondeveloper
  • rondeveloper
    Ron's learning record
    rondeveloper
  • 전체
    오늘
    어제
    • 분류 전체보기 (103) N
      • k8s (3) N
      • AWS (1)
      • 리눅스 (5)
      • Docker (8)
      • 라이브러리 & 프레임워크 (14)
        • React (2)
        • NestJS (8)
        • Spring (0)
        • Django (3)
        • FastAPI (1)
      • 웹 (2)
        • Nginx (1)
      • 프로그래밍 언어 (29)
        • HTML (0)
        • CSS (0)
        • JavaScript (21)
        • Python (3)
        • Node.js (0)
        • TypeScript (4)
        • Java (1)
      • Today I learned (9)
      • 알고리즘 (9)
        • 백준 (0)
        • 프로그래머스 (8)
        • 개념 (1)
      • 티끌모아 태산 (5)
        • 하루에 영단어 하나씩 (5)
        • 독서 (0)
      • 시행착오 (3)
      • 데이터베이스 (2)
        • MySQL (0)
      • 컴퓨터 과학 (8)
        • 네트워크 (2)
        • 운영체제 (0)
        • 데이터베이스 (2)
        • 자료구조 (4)
      • 포트폴리오 (4)
        • JJINCAFE IN SEOUL (4)
        • CODEUNICORN (0)
      • 회고 (0)
      • CICD (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자바스크립트
    typescript
    조인
    레벨2
    네트워크
    Kubectl
    typeorm
    반복문
    mysql
    FastAPI
    생활코딩
    Docker
    기초
    Kubernetes
    Python
    프로그래머스
    도커
    redis
    리눅스
    IP 주소
    컨테이너
    javascript
    Til
    iterable
    nestjs
    스택
    모듈
    배열
    django
    코딩테스트
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
rondeveloper
Validation
상단으로

티스토리툴바