[Nest.js] swagger 적용하기

Woong·2022년 12월 16일
0

Nestjs

목록 보기
16/28

설치

npm install --save @nestjs/swagger

적용

  • main.ts 에서 SwaggerModule 을 부트스트래핑
    • 이 상태로 서버를 올리면 /api 에서 API 문서 확인
    • /api-json 을 통해 JSON 파일로 다운로드
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}
bootstrap();
  • Controller 에서 API 상세정보 지정
@ApiOperation({ summary: '등록' })
@ApiResponse({
  status: 500,
  description: 'server error'
})
@ApiResponse({
  status: 200,
  description: 'success',
  type: ReadonlyUserDto
})
@Post()
createUser(@Body dto: UserDto) {
  ...
}
  • DTO 에 API 프로퍼티 지정
export class UserDto {
  @ApiProperty({
    example: '',
    description: '',
    required: true
  })
  email: string;
  // 타입 지정
  @ApiProperty({ type: Number })
  age: number;
  // 배열
  @ApiProperty({ type: [String] })
  names: string[];
  // 열거형
  @ApiProperty({
    enum: ['Admin', 'Moderator', 'User']
  })
  role: UserRole;

}

reference

0개의 댓글