프로그래밍/백엔드

[Nest.js] main.ts에서 swagger 파일 분리하기

이불이! 2022. 11. 24. 15:34
728x90

공식 문서를 보면 main.ts 파일에 swagger 설정을 하고 있다.
하지만 main.ts에는 swagger만 있는 것이 아니니 파일을 분리하도록 하겠다.

main.ts의 기본적으로 생성되는 코드는 아래와 같다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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


원래는 아래처럼 하려고 했으나 swaggerConfig(app)에서 에러가 발생했다.

Argument of type 'INestApplication' is not assignable to parameter of type 'NestApplication'.
Type 'INestApplication' is missing the following properties from type 'NestApplication': httpAdapter, config, appOptions, logger, and 47 more.ts(2345)
 
해석해보면 NestApplication 타입이 필요하다는 이야기다.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { swaggerConfig } from './swagger';

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

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

bootstrap();


아래와 같은 코드로 변경하여 swagger파일을 import 시키겠다.

swagger.ts

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

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

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

bootstrap();

- NestFactory: Nest 애플리케이션 인스턴스를 생성하기 위한 클래스

 

혹은 swagger 파일 안에 INestApplication을 리턴 값으로 주고 main.ts에는 원래 코드로 돌려놓는다.

swagger.ts

import { INestApplication } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

export const swaggerConfig = (app: INestApplication) => {
  const config = new DocumentBuilder()
	...
    .setVersion('1.0')
    .build();

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

 

main.ts

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

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

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

Reference
NestFactory 파헤치기 https://velog.io/@koo8624/NestJS-%ED%8C%8C%ED%97%A4%EC%B9%98%EA%B8%B0-01.-NestFactory-NestApplication

 

[NestJS 파헤치기] 01. NestFactory

이번에는 그 첫 시간으로 모든 NestJS 어플리케이션의 진입점에 해당하는 NestFactory 클래스에 대해 살펴보도록 하겠습니다.

velog.io