저장을 습관화

NestJS - Swagger 데코레이더 정리 본문

공부/node.js

NestJS - Swagger 데코레이더 정리

ctrs 2024. 1. 9. 22:55

이전 게시글 : https://ctrs.tistory.com/433

 

NestJS - Swagger를 사용해서 API 문서 만들기

NestJS 공식 문서 swagger 관련 https://docs.nestjs.com/openapi/introduction Documentation | NestJS - A progressive Node.js framework Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript,

ctrs.tistory.com

 

공식문서 : https://docs.nestjs.com/openapi/introduction

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

공식 문서는 있으나 아쉽게도 각 데코레이터에 대한 설명은 부족하다.

 

1. @ApiTags

@ApiTags(목차)
@Controller(URL)

 

@ApiTags('USER') 와 같이 작성하며 각 컨트롤러 탭의 목차가 된다.

 

각 컨트롤러 파일마다 이 데코레이터가 없다면

swagger 페이지의 default 목차에서 모든 API 내용이 나올 것이다.

 

 

2. @ApiOperation

@ApiOperation({ summary: 'API 설명' })
@Post()

 

@ApiOeration({ summary: '회원가입' })과 같이 작성하며

각 API의 용도, 설명을 작성할 수 있다.

 

 

3. @ApiProperty

주로 DTO 파일에 작성하며 테스트이 입력값에 대한 예시를 작성할 수 있다.

- signup.request.dtop.ts

export class SignUpRequestDto extends PickType(Users, [
  'email', 'nickname', 'password'
] as const) {}

 

- users.entity.ts

// ...
@ApiProperty({ example: 1, description: '사용자 아이디' })
  @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
  id: number;

  @IsEmail()
  @ApiProperty({
    example: 'test@email.com',
    description: '이메일 입력',
    required: true,
  })
  @Column('varchar', { name: 'email', unique: true, length: 30 })
  email: string;

  @IsString()
  @IsNotEmpty()
  @ApiProperty({
    example: 'testUser',
    description: '닉네임 입력',
    required: true,
  })
  @Column('varchar', { name: 'nickname', length: 30 })
  nickname: string;

  @IsString()
  @IsNotEmpty()
  @ApiProperty({
    example: 'test1234!@#$',
    description: '패스워드 입력',
    required: true,
  })
  @Column('varchar', { name: 'password', length: 100, select: false })
  password: string;
// ...

 

swagger 기본 페이지

 

'Try in out'

 

swagger 하단 'Schemas' 탭

 

즉 각 API에 대한 입력 테스트에 대한 예시를 적을때는 DTO를 작성해야 한다.

 

 

4. @ApiResponse

swagger에서 API를 테스트 하였을때 response, 반환되는 내용을 확인할 수 내용을 설정하는 데코레이션이다.

 

이 데코레이션이 없다면 아래와 같이 HTTP status code 201만이 나올 것이다.

 

- users.controller.ts

// ...
@ApiResponse({
    status: 200,
    description: '성공',
    type: UserDto,
  })
  @ApiOperation({ summary: '로그인' })
  @Post('login')
  logIn(@User() user: Users) {
    console.log(`${user.email} 로그인 성공!`);
    return `${user.email} 로그인 성공!`;
  }
// ...

 

- user.dto.ts

export class UserDto extends SignUpRequestDto {
  @ApiProperty({
    required: true,
    example: 1,
    description: '아이디',
  })
  id: number;
}

 

 

이러한 상태로 보았을떄 swagger를 이용해서 모든 API를 테스트할때에는 

각각 API에 대한 DTO가 필요하다.

API에 올바른 값과 함께 시도했을때의 성공에 대한 Response(201 등..)

잘못된 값과 함께 시도했을 때의 실패에 대한 Response(400, 401, 403 등..)