[Nest.JS] Nest 이용해서 Swagger 문서 작성하기

JUNHO YEOM·2022년 10월 11일
0

Nest.JS

목록 보기
3/7
post-thumbnail

Nest에는 swagger 데코레이터를 이용하여 json, yaml 형식으로 따로 작성하지 않고도 Docs 작성이 가능하다.
그래서 데코레이터를 최대한 사용해서 Docs를 작성하는 것을 목표로 했다.


유저 조회 Swagger API Docs

작성한 코드는 다음과 같다.

  /**
   * @Summary 유저 조회 API
   * @param email
   * @returns User
   */
  @Get()
  @ApiOperation({
    description: '유저 이메일을 인자로 받아 유저 정보를 반환합니다.',
    summary: '유저 조회',
  })
  @ApiOkResponse({
    type: User,
    description: '유저 조회에 성공하였습니다.',
  })
  @ApiNotFoundResponse({
    type: UserError,
    description: '존재하지 않는 이메일입니다.',
  })
  async findOne(@Query('email') email: string): Promise<User> {
    const result = await this.usersService.findOne({
      email,
    });
    delete result.password;
    return result;
  }

일단 완성은 했지만 코드가 너무 난잡해보이는데...? 이게 맞나...? 라는 생각을 잠시 했지만,
사실 더 나은 방법이 생각나지 않는걸...


@APIOperation

  @ApiOperation({
    description: '유저 이메일을 인자로 받아 유저 정보를 반환합니다.',
    summary: '유저 조회',
  })

해당 API를 설명해 주는 역할을 한다.


@ApiOkResponse

  @ApiOkResponse({
    type: User,
    description: '유저 조회에 성공하였습니다.',
  })

200 코드의 응답을 리턴할 때의 Docs를 추가한다.


@ApiNotFoundResponse

  @ApiNotFoundResponse({
    type: User404Error,
    description: '존재하지 않는 이메일입니다.',
  })

404 코드의 응답을 리턴할 때 Docs를 추가한다.


Example Value

// users.controller.ts
  @ApiOkResponse({
    type: User,
    description: '유저 조회에 성공하였습니다.',
  })

Example Value 부분은 Response 데코레이터의 type option을 통해서 넣어 줄 수 있다.
해당하는 class에 @ApiProperty를 이용하여 예시 값을 넣어 줄 수 있다.

// user.entity.ts
export class User {
  @ApiProperty({ example: 'jhyeom1545@gmail.com' })
  @PrimaryColumn({
    unique: true,
  })
  email: string;

  @Column()
  password: string;

  @ApiProperty({ example: '홍길동' })
  @Column()
  name: string;

  @ApiProperty({ example: 500 })
  @Column()
  points?: number;

  @ApiProperty({ example: '2022-10-11T18:47:32.165Z' })
  @CreateDateColumn()
  createdAt: Date;

  @ApiProperty({ example: '2022-10-11T18:47:32.165Z' })
  @UpdateDateColumn()
  updatedAt: Date;

  @ApiProperty({ example: null })
  @DeleteDateColumn()
  deletedAt: Date;
}

Error를 반환하는 부분은 따로 작성해서 넣어주었다.

export class User404Error {
  @ApiProperty({ example: 404 })
  statusCode: number;

  @ApiProperty({ example: '존재하지 않는 이메일입니다.' })
  message: string;

  @ApiProperty({ example: 'Not Found' })
  error: string;
}

참고

https://docs.nestjs.com/openapi/operations#responses
https://docs.nestjs.com/openapi/cli-plugin#comments-introspection

0개의 댓글