본문 바로가기

framework/NestJs

[NestJs] swagger 예시

npm 설치

npm i @nestjs/swagger

예시 시작

main.ts에서 swagger 모듈 설정

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: true,
  });

  // swagger 모듈 설정 시작
  // npm i @nestjs/swagger
  const config = new DocumentBuilder()
    // 페이지 명
    .setTitle('Cats Example')
    // 버전
    .setVersion('1.0')
    // 페이지 설명
    .setDescription('this is cat API')
    // 소분류 추가
    .addTag('cats')
    .build();
  // document 생성
  const document = SwaggerModule.createDocument(app, config);
  // 경로가 api일 때 생성한 document 페이지 설정
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}
bootstrap();

결과 페이지 - http://localhost:3000/api

request 변수 설명

추후에 request, response dto에 Cats 스키마를 extends 받아서 사용하면 코드가 clean하다.

import { Prop, Schema, SchemaFactory, SchemaOptions } from '@nestjs/mongoose';
import { IsNotEmpty, IsString } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

const options: SchemaOptions = {
  timestamps: true,
};

@Schema(options)
export class Cats {
  @Prop({
    unique: true,
    required: true,
  })
  @IsNotEmpty()
  @IsString()
  // swagger 설정
  @ApiProperty({
    // 필수값
    required: true,
    // 유니크
    uniqueItems: true,
    // 예시
    example: 'ididid',
    // 설명
    description: 'This is cats id',
  })
  id: string;
}

export const CatsSchema = SchemaFactory.createForClass(Cats);

 

공식 사이트(swagger 부분) : https://docs.nestjs.com/openapi/introduction

'framework > NestJs' 카테고리의 다른 글

[NestJs] JWT 사용  (0) 2023.04.05
[NestJs] 디자인 패턴 적용  (0) 2023.03.30
[NestJs] Mongoose - 스키마, Insert  (0) 2023.03.29
[NestJs] npm 명령어  (0) 2023.03.29