서크호
서크호 - 개발 스토리
서크호
전체 방문자
오늘
어제
  • 분류 전체보기 (22)
    • TEAM 알고싶다 (17)
      • 성공 문제 (16)
      • 실패 문제 (1)
    • JavaScript (0)
    • TypeScript (0)
    • Node.js (2)
      • React.js (0)
      • Next.js (0)
      • NestJS (2)
    • Baekjoon (Node.Js) (1)
    • Error Box (1)
    • MySQL (1)
    • JAVA (0)
    • Andriod (0)
    • Spring Boot (0)

블로그 메뉴

  • 홈

공지사항

인기 글

태그

  • 백준
  • 10026
  • 적록색약 javascript
  • 10026 node
  • Nest Typeormm
  • 적록색약 nodejs
  • Nestjs
  • NestJS ValidationPipe
  • NestJs Strategy
  • Nest mysql
  • javascript
  • Nest DB
  • 백준 적록색약
  • nodejs
  • NestJs login
  • NestJs PassPort
  • NestJs session

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
서크호

서크호 - 개발 스토리

[NestJS] ValidationPipe를 이용해 Request 편하게 검증하기 (class-validator)
Node.js/NestJS

[NestJS] ValidationPipe를 이용해 Request 편하게 검증하기 (class-validator)

2023. 8. 23. 12:12

전제 조건

- controller를 만들어 놨다. (전혀 상관 없다. 그냥 이 글에 시작점이 여기라 적어놨다.)

- dto를 만들어 놨다.

- 전역으로 선언해주는 방식도 있지만 여기서는 다루지 않는다.

 

시작

1. 각종 디펜던시를 설치한다.

 - dependencies

"class-validator",
"class-transformer"

 

2. 적용할 dto 안에서 임포트 해주고 적절한 데코레이터를 사용해준다.

 - 여기에 선언해준 key들은 참고만 해주면 된다.

import { IsNotEmpty, IsString, Length, Matches } from "class-validator";

export class createUserDto {

    @IsNotEmpty()
    @IsString()
    @Matches(RegExp(/^[A-Za-z]{1}[A-Za-z0-9]{3,19}$/))
    USER_ID: string;

    @IsNotEmpty()
    @IsString()
    @Matches(RegExp(/^(?=.*[a-zA-Z])(?=.*[!@#$%^*+=-])(?=.*[0-9]).{8,20}$/))
    // @Matches(/^[A-Za-z\d!@#$%^&*()]{8,30}$/, {message:"ㄹㅇㄴㅁ"})
    USER_PW: string;

    @IsNotEmpty()
    @IsString()
    @Length(11,11)
    USER_PHONE: string;

    @IsNotEmpty()
    @IsString()
    USER_NICKNAME: string;

}

 

3. 컨트롤러에 넣어주면 끝이다 너무 간단하다.

 - ValidationPipe, Dto 를 임포트 @Body 데코레이터에 넣어주는 부분만 보면 된다.

import { Body, Controller, Post, ValidationPipe } from '@nestjs/common';
import { UserService } from './user.service';
import { createUserDto } from './dto/create.user.dto';

@Controller('user')
export class UserController {

    constructor(
        private readonly userService: UserService
    ) {};

    @Post('/create')
    create(@Body(ValidationPipe) createUserDto: createUserDto) : createUserDto{
        this.userService.create(createUserDto)
        return createUserDto;
    }
}

 

4. 테스트용을 따로 만들어보고 테스트 해보자

- create.user.dto.ts

- @IsNotEmpty 데코레이터로 빈값을 보내면 에러를 뱉어야 한다.

import { IsNotEmpty } from "class-validator";
export class createUserDto {
    @IsNotEmpty()
    USER_ID: string;
    @IsNotEmpty()
    USER_PW: string;
    @IsNotEmpty()
    USER_PHONE: string;
    @IsNotEmpty()
    USER_NICKNAME: string;
}

- user.controller.ts

- 위에서 설명한 것과 동일하게 @Body 안에 ValidationPipe를 넣어주고 받는 값을 class-validator 가 적용되어있는 createUserDto로 만들어줬다.

- ValidationPipe가 잘 걸러준다면 Dto에서 정한 키들이 모두 값이 있지 않으면 에러를 뱉어낼거다.

- ValidationPipe를 통과한다면 받은 req를 그대로 뱉어주는 간단한 코드이다.

import { Body, Controller, Post, Request, ValidationPipe } from '@nestjs/common';
import { UserService } from './user.service';
import { createUserDto } from './dto/create.user.dto';
createUserDto
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post('/create')
  create(@Body(ValidationPipe) test: createUserDto) : createUserDto{
    return test
  }
}

- 직접 한 번 보자 (글쓴이는 Postman 이용)

키 값이 모두 있어서 잘 뱉어준다.
USER_ID를 공백으로 보내니 에러를 잘 뱉어준다.
그렇다 너무 잘 뱉어준다.

- 여기서는 ID, PW 공백일 떄 에러를 뱉어주고 마무리한다.

- 하지만 실제로 코드를 작성할 때는 내가 dto에 정해준 데코레이터들이 유효성 검사를 잘 해주는지 키마다 모두 꼭 확인해줘야 한다. 

저작자표시 (새창열림)

'Node.js > NestJS' 카테고리의 다른 글

[NestJS] Passport.js와 session을 사용해 로그인 인증 구현하기  (2) 2023.09.03
    'Node.js/NestJS' 카테고리의 다른 글
    • [NestJS] Passport.js와 session을 사용해 로그인 인증 구현하기
    서크호
    서크호
    팀 스터디 및 개인 개발 관련 블로그 입니다!

    티스토리툴바