[Nest.js] Pipe를 이용한 유효성 체크

sookyung kang·2023년 3월 16일

Nest.js

목록 보기
8/8
post-thumbnail

파이프를 이용해 게시물 생성시 유효성 체크

필요한 모듈

class-validator, class-transformer
npm install class-validator class-transformer --save

*참고 document
https://github.com/typestack/class-validator#manual-validation

파이프 생성하기

현재는 게시물에 title과 description이 없어도 게시물이 생성됩니다.
이 부분을 파이프를 통해 수정해줍니다.

create-board.dto.ts 파일에서

import { IsNotEmpty } from "class-validator";

export class CreateBoardDto {
    
    @IsNotEmpty()
    title: string;

    @IsNotEmpty()
    description: string;
}

위와 같이 작성하여 줍니다.

그리고 boards.controller.ts의 createBoard를

 @Post('/')
    @UsePipes(ValidationPipe)
    createBoard(
        @Body() createBoardDto : CreateBoardDto
    ): Board {
        return this.boardsService.createBoard(createBoardDto);
    }

위와 같이 수정하여 줍니다.

Postman 에서 title이 빈 상태로 요청을 보내보면

위와 같이 error message가 나오게 됩니다.

특정 게시물을 찾을 때 없는 경우 결과 값 처리

기존 특정 아이디로 쓰여진 게시물을 찾을때 아무런 에러메세지가 나타나지 않습니다.

board.service.ts의 getBoardByID를

getBoardByID(id: string) : Board {
        
        const found = this.boards.find((board) => board.id === id);

        if(!found){
            throw new NotFoundException();
        }
        return found;
    }

위와 같이 작성하여 줍니다.

Postman에서 이제 다시 확인해보면

에러메세지가 뜨게 됩니다.

에러메세지를 정하고 싶다면

NotFoundException() 안에 넣으면 됩니다.

0개의 댓글