Tech Blog of Pinomaker
article thumbnail
Published 2023. 10. 9. 01:14
Nestjs Swagger(1) - Swagger 설정 B.E/Nest JS

 

 

API Documentation & Design Tools for Teams | Swagger

Loved by all • Big & Small Thousands of teams worldwide trust Swagger to deliver better products, faster.

swagger.io

 

 

Swagger는 API를 쉽게 문서화를 시킬 수 있는 라이브러리 입니다. Swagger를 사용하면 코드레벨에서 API 문서를 작성하고 동기화할 수 있어 어렵지 않게 API를 실시간으로 관리할 수 있다는 장점이 있으며, API를 사용해야하는 유저들은 Swagger에서 테스트를 할 수 있다는 장점이 있습니다.

 

오늘은 Nestjs에서 Swagger를 사용하는 방법에 대해 알아봅니다.

 

0. 의존성 모듈 설치

먼저 Swagger를 사용하기 위한 의존성 모듈들을 설치합니다. express기반인지 fastify 기반인지에 따라서 필요한 의존성이 달라집니다. 저는 express를 기반으로 포스팅하겠습니다.

# express nest
yarn add @nestjs/swagger swagger-ui-express

# fastify nest
yarn add @nestjs/swagger fastify-swagger

 

1. Swagger 설정 파일 생성

먼저 Swagger 설정 파일을 생성하고 작성합니다. 저는 accessToken도 사용하여 인증 인가처리를 하기에 해당 설정도 넣었으며, /api-docs를 swagger 접속 주소로 지정하였습니다.

// src/config/swaggerConfig.ts

// ** Nest Imoorts
import { INestApplication } from '@nestjs/common';

// ** Swagger Imports
import {
  SwaggerModule,
  DocumentBuilder,
  SwaggerCustomOptions,
} from '@nestjs/swagger';

const swaggerCustomOptions: SwaggerCustomOptions = {
  swaggerOptions: {
    persistAuthorization: true,
  },
};

const swaggerConfig = (app: INestApplication): void => {
  const options = new DocumentBuilder()
    .setTitle('DICE API') // title 설정
    .setDescription('api document of dice project') // description 설정
    .setVersion('1.0.0') // version 설정
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'Bearer',
        name: 'JWT',
        in: 'header',
      },
      'access-token',
    )
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api-docs', app, document, swaggerCustomOptions);
};

export default swaggerConfig;

 

2. Swagger 적용하기

이제 src/main.ts에 Swagger를 아래와 같이 적용하면 Swagger 설정은 끝 입니다. Swagger는 Production에서는 노출되면 위험하므로, 저는 실행환경이 dev일 경우에만 Swagger를 실행시켰는 데 자유롭게 사용하시면 됩니다.

// src/main.ts

// ** Nest Imports
import { NestFactory } from '@nestjs/core';

// ** Custom Module Imports
import { AppModule } from './app.module';

// ** Swagger Config Imports
import swaggerConfig from './config/swaggerConfig';

// ** Express Imports
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  // ** Server Container 생성
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    bufferLogs: true,
    snapshot: true,
  });

  // ** Swagger Setting
  if (process.env.NODE_ENV === 'dev') {
    swaggerConfig(app); // 실행 환경이 dev일 경우에만 실행
  }

  // ** Server ON Handler
  await app.listen(process.env.SERVER_PORT);
}
bootstrap();

 

 

profile

Tech Blog of Pinomaker

@pinomaker

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!