본문 바로가기
개발 프레임워크/NestJS

[NestJS] OpenAPI

by minhyeok.lee 2023. 2. 7.
반응형

OpenAPI란?

RESTfulAPI를 설명하는 데 사용되는 언어 독립적인 정의 형식이다.

Nest는 데코레이터를 활용하여 이러한 사양을 생성할 수 있는 전용 모듈을 제공한다.

 

NestJS -> OpenAPI 문서

https://swagger.io/specification/

 

OpenAPI Specification - Version 3.0.3 | Swagger

OpenAPI Specification Version 3.1.0 The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 RFC2119 RF

swagger.io

 

설치

사용하기 위한 종속성 설치 명령어

$ npm install --save @nestjs/swagger

 

Swagger 설정 및 실행

2023.02.06 - [개발 프레임워크/NestJS] - [NestJS] 스웨거(Swagger)

 

[NestJS] 스웨거(Swagger)

NestJS 형상관리 도구_스웨거(Swagger) Swagger는 API 문서 자동화 도구이다. 1. API 문서를 따로 작성할 필요 없다. 2. 만약에 코드와 API 문서를 따로 관리하게 되면 코드를 수정하였는데 API 문서 최신화

kfdd6630.tistory.com

 

메소드에 의해 반환되는 document OpenAPI 문서의 SwaggerModule#createDocument()를 준수하는 직렬화 가능 개체이다.

 HTTP를 통해 호스팅하는 대신 JSON/YAML 파일로 저장하고 다양한 방식으로 사용할 수도 있다.

 

 

DocumentBuilder는 OpenAPI 사양을 준수하는 기본 문서를 구성하는 데 도움이 된다.

제목, 설명, 버전 등과 같은 속성을 설정할 수 있는 여러 메서드를 제공한다.

 

전체 문서(모든 HTTP 경로가 정의됨)를 만들기 위해 SwaggerModule 클래스의 createDocument() 메서드를 사용한다.

이 메서드는 애플리케이션 인스턴스와 Swagger 옵션 개체라는 두 가지 인수를 사용한다.

또는 SwaggerDocumentOptions 유형이어야 하는 세 번째 인수를 제공할 수 있다.

 

문서를 생성하면 setup() 메서드를 호출할 수 있고 그것은 아래 사항들을 받아들일 수 있다.
1. Swagger UI를 마운트하는 경로 (The path to mount the Swagger UI)
2. 애플리케이션 인스턴스 (An application instance)
3. 위에 인스턴스화된 문서 객체 (The document object instantiated above)
4. 선택적 구성 매개변수 (Optional configuration parameter)

 

 

* SwaggerDocumentOptions(스웨거 문서옵션)

문서를 만들 때 라이브러리의 동작을 미세 조정하기 위한 몇 가지 추가 옵션을 제공할 수 있습니다. 이러한 옵션은 SwaggerDocumentOptions 유형이어야하며 다음과 같다.

export interface SwaggerDocumentOptions {
  /**
   * 사양에 포함할 모듈 목록
   */
  include?: Function[];

  /**
   * 추가로 검사하여 사양에 포함해야 하는 추가 모델
   */
  extraModels?: Function[];

  /**
   * `true`인 경우 swagger는 `setGlobalPrefix()` 메서드를 통해 설정된 전역 접두사를 무시
   */
  ignoreGlobalPrefix?: boolean;

  /**
   * `true`인 경우 swagger는 `include` 모듈에서 가져온 모듈의 경로도 불러옴
   */
  deepScanRoutes?: boolean;

  /**
   * `operationId`를 생성하는 데 사용하는 사용자 정의 operationIdFactory
   * `controllerKey` 및 `methodKey` 기반
   * @default () => controllerKey_methodKey
   */
  operationIdFactory?: (controllerKey: string, methodKey: string) => string;
}

 

예를 들어 라이브러리가 createUser대신 와 같은 작업 이름을 생성 UserController_createUser하도록 하려면 다음을 설정 가능

const options: SwaggerDocumentOptions =  {
  operationIdFactory: (
    controllerKey: string,
    methodKey: string
  ) => methodKey
};
const document = SwaggerModule.createDocument(app, config, options);

 

* ExpressSwaggerCustomOptions(설정 옵션)

ExpressSwaggerCustomOptions(express를 사용하는 경우) 인터페이스를 SwaggerModule#setup 메서드의 네 번째 인수로 이행하는 옵션 개체를 전달하여 Swagger UI를 구성할 수 있다.

export interface ExpressSwaggerCustomOptions {
  explorer?: boolean;
  swaggerOptions?: Record<string, any>;
  customCss?: string;
  customCssUrl?: string;
  customJs?: string;
  customfavIcon?: string;
  swaggerUrl?: string;
  customSiteTitle?: string;
  validatorUrl?: string;
  url?: string;
  urls?: Record<'url' | 'name', string>[];
}

 

해당 작업 예제를 보고 싶을 때, 아래 링크 확인

https://github.com/nestjs/nest/tree/master/sample/11-swagger

 

GitHub - nestjs/nest: A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applica

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications on top of TypeScript & JavaScript (ES6, ES7, ES8) 🚀 - GitHub - nestjs/nest: A pro...

github.com

 

 

* 주의
fastify와 helmet을 사용할 때 CSP에 문제가 있을 수 있으므로 이 충돌을 해결하려면 아래와 같이 CSP를 구성하자.

app.register(helmet, {
  contentSecurityPolicy: {
    directives: {
      defaultSrc: [`'self'`],
      styleSrc: [`'self'`, `'unsafe-inline'`],
      imgSrc: [`'self'`, 'data:', 'validator.swagger.io'],
      scriptSrc: [`'self'`, `https: 'unsafe-inline'`],
    },
  },
});

// CSP를 전혀 사용하지 않을 경우 다음과 같이 적용
app.register(helmet, {
  contentSecurityPolicy: false,
});
반응형

댓글