Nest로 API 구현하기(4) - Pipe

Lojy·2022년 7월 3일
1

Nest

목록 보기
4/5
post-thumbnail

Pipe

Pipe 란?

  • @Injectable() 데코레이터로 주석이 달린 클래스이다.
  • data transfomation과 data validation을 위해서 사용 된다.
  • 컨트롤러 경로 처리기에 의해 처리되는 인수에 대해 작동한다.

Data Transformation

입력데이터를 원하는 형식으로 변환한다.
예를들어 숫자를 받길 원하는데 문자열 형식으로 온다면 파이프를 자동으로 숫자로 바꿔준다.('7'로 들어오면 7로 변환)

Data Validation

입력데이터를 평가하고 유효한 경우 변경되지 않은 상태로 전달하면된다. 그렇지 않으면 데이터가 올바르지 않을 때 예외를 발생 시킨다.
예를 들어 아이디의 길이가 10자 이하여야 하는데 10자 이상일 경우 에러 발생

Pipe 사용법

Pipe를 사용하는 방법은 세가지로 나눠 질수 있다.
Handler-level Pipes, Parameter-level Pipes, Global-level Pipes 이다.

Handler-level Pipes

핸들러 레벨에서 @UsePipes() 데코레이터를 이용하여 사용 가능하다.(모든 파라미터에서 적용)

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

Parameter-level Pipes

파라미터 레벨 파이프 이기에 특정한 파라미터에만 적용할 수 있다.

@Post()
createBoard(
    @Body('title', ParameterPipe) title: string,
    @Body('description') description: string,
    ): Board {
    return this.boardsService.createBoard(title, description);
}

Global Pipes

글로벌 파이프로 애플리케이션 레벨의 파이프이다. 클라이언트에서 들어오는 모든 요청에 적용된다.

main.ts

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

Built-in Pipes

Nest에서 기본적으로 사용할 수 있게 만들어 놓은 6가지 파이프

  • ValidationPipe
  • ParseIntPipe
  • ParseBoolPipe
  • ParseArrayPipe
  • ParseUUIDPipe
  • DefaultValuePipe

파이프를 이용한 유효성 체크

모듈 설치

npm i class-validator class-transformer --save

파이프 생성하기(Handle-levle Pipe)

게시물을 생성할 때 제목과 설명에 아무런 값을 주지 않아도 문제없이 생성이 되기때문에 파이프를 추가해준다.

./boards/dto/createBoard.dto.ts

import { IsNotEmpty } from 'class-validator';

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

dto파일에서 우선 빈문자열인지 확인.
@IsNotEmpty() 는 빈값을 허용하지 않는다.
참조: Documentation

./boards/boards.controller.ts

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

핸들러에서 @UsePipes를 이용하여 유효성을 체크한다.

  • Thunder Client에서 확인 결과

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

게시물을 ID로 가져 올때 만약 없는 ID의 게시물을 가져오려고 하면 결과값으로 아무 내용이 없이 돌아오는데 게시물이 없으면 없다고 클라이언트로 다시 전달

./boards/boards.service.ts

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

    if(!found) {
        throw new NotFoundException(`Can't find Board with id ${id}`);
    }
    return found;
}

찾는 게시물이 없을 때 예외 인스턴스를 생성해서 이용하면 된다.

없는 게시물을 지우려 할 때 결과 값 처리

앞서 특정 게시물을 ID로 가져올 때 만약 없는 ID의 게시물을 가져오려고 하면 에러 값을 전달했듯이 없는 게시물을 지우려 할 때도 에러 값을 줌.

./src/boards/boards.service.ts

deleteBoard(id: string): void {
    const found = this.getBoardById(id)
    this.boards = this.boards.filter((board) => board.id !== found.id);
}

특정 게시물 찾을 때 사용했던 getBoardById 메소드를 이용하여 지우려고 하는 게시물이 있는지 체크 하고, 있으면 지우고 없으면 에러 메세지를 보낸다.

마무리

오늘은 Pipe에 대해 배워 보았다. Express에서는 유효성 체크를 하나하나 체크 해줬던거 같은데 Nest에서는 모듈을 이용하여 체크 해줄 수 있어 편한거 같다.

[참조: 따라하며 배우는 NestJS]

profile
Node 하는 lojy

0개의 댓글