NestJS 에 있는 "ValidationPipe" 를 이용하면 유효성 검사를 할 수 있다.
"ValidationPipe" 를 이용하기 위해서 아래 두개의 라이브러리를 설치해야한다.
$ npm i --save class-validator class-transformer
자동으로 적용하기 위해 main.ts 에 아래와 같이 입력
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { initializeTransactionalContext } from 'typeorm-transactional';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
initializeTransactionalContext(); // Transactional 을 이용하기 위해 선언
const app = await NestFactory.create(AppModule);
// 자동으로 validation을 확인하기 위해 선언
app.useGlobalPipes(
new ValidationPipe({
transform: true, //class-transform 을 사용하기위한 설정
}),
);
await app.listen(3000);
}
bootstrap();
- option 설명
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // 미리 정의되지 않은 필드를 자동으로 제거합니다.
transform: true, // 클라이언트로부터 받은 데이터를 DTO 인스턴스로 자동 변환합니다.
forbidNonWhitelisted: true, // DTO에 정의되지 않은 필드가 포함되어 있을 경우 요청을 거부합니다.
disableErrorMessages: false, // 개발 중 오류 메시지를 표시하여 디버깅을 도움니다.
}));
다음으로 Entity에 설정하여 유효성 테스트하는 방법
예시 1
import { validate, validateOrReject, Contains, Length,} from 'class-validator';
import { PrimaryGeneratedColumn, Column} from 'typeorm'
import { Transactional } from 'typeorm-transactional';
import { plainToClass } from 'class-transformer';
// entity
export class Board {
@PrimaryGeneratedColumn()
id: number;
@Length(10, 20)
@Column
title: string;
@Contains('hello')
@Column
text: string;
}
// dto
export class CreatePostRequestDto{
title: string;
text: string;
}
@Transactional()
async create(createPostRequestDto: CreatePostRequestDto) {
const newPost = plainToClass(Board, createPostRequestDto); // transformer 이용
const postValidation = await validate(newPost); //validation 확인
if (postValidation.length > 0) {
throw new BadRequestException(`validation failed. errors: ${postValidation}`);
}
}
입력예시
createPostRequestDto = {
title: "hi",
text: "validation test"
}
에러출력
{
"message": "validation failed. errors: An instance of Board has failed the validation:\n - property title has failed the following constraints: isLength \n",
"error": "Bad Request",
"statusCode": 400
}
예시 2 : Dto 에 제약을 설정
....
export CreatePostRequestDto{
@Length(10, 20) // 추가
title: string;
text: string;
}
@Transactional()
async create(createPostRequestDto: CreatePostRequestDto) {
....
}
같은 입력을 주면 아래에 따로 validation을 확인 할 필요없이 에러문구가 아래와 같이 뜬다.
{
"message": [
"title must be longer than or equal to 5 characters"
],
"error": "Bad Request",
"statusCode": 400
}
참고자료
'프로그래밍 > Nest.js' 카테고리의 다른 글
[ Webstrom ] NestJS 디버깅하는 법 (0) | 2024.05.04 |
---|---|
[ NestJS] 유효성 검사를 위한 DTO 설정 예시 (0) | 2024.05.03 |
[ NestJS ] HTTP exceptions 종류 기록 (0) | 2024.05.02 |
[NestJS] [ 게시판 ] Entity 관계 기록 (0) | 2024.04.30 |
[ NestJS ] [ TypeORM ] DB 삭제, 수정, 생성 시간 남기기 (0) | 2024.04.29 |