[NestJS] NestJS 에 swagger 달기
프로젝트 진행 중 작성한 wiki 를 옮겨와 편집했습니다.
swagger
OpenAPI Speciation (OAS) 를 활용할 수 있는 도구.
OpenAPI 란 RESTful 인터페이스를 정의하기 위한 세계 표준이다. OAS 로 technology-agnostic API 를 설하고 개발, 사용할 수 있다.
Use in nest!
yarn add @nestjs/swagger
nest 는 OpenAPI 를 데코레이터로 만들 수 있는 모듈을 제공한다.
DocumentBuilder
로 OpenAPI 사양을 준수하는 기본 문서를 구축할 수 있다. 전체문서 (all HTTP routes defined) 를 생성하려면 SwaggerModule
의 createDocument()
를 사용한다. 순서대로 application, Swagger option, SwaggerDocumentOptions 객체를 인자로 받는다.
문서를 만들고 setup()
메소드를 호출할 수 있다. 인자 순서는 다음과 같다.
- The path to mount the Swagger UI
- An application instance
- The document object instantiated above
- Optional configuration parameter (read more here)
main.ts
const config = new DocumentBuilder()
.setTitle('GhostPong API')
.setDescription('The GhostPong API description')
.setVersion('1.0')
.addTag('GhostPong')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
기본 설정 후 start 하면 다음과 같은 페이지가 만들어진다.
/api-json
, /api-yaml
으로 각각 json, yaml 형식으로 데이터를 받을 수도 있다.
CLI 플러그인
DTO를 자동으로 detect 해준다.
- 모든 DTO 프로퍼티에
@ApiHideProperty
를 사용하지 않는 한@ApiProperty
로 주석을 달아줌 - 물음표에 따라 필요한 프로퍼티를 설정 (e.g.
name?: string
will setrequired: false
). - 유형에 따라
type
orenum
속성을 설정(배열도 지원). - 할당된 기본값에 따라
default
속성을 설정 class-validator
데코레이터를 기반으로 여러 유효성 검사 규칙을 설정(classValidatorShim
이true
로 설정된 경우).- 적절한 상태와
type
(response model)으로 모든 엔드포인트에 응답 데코레이터를 추가 - 주석을 기반으로 속성 및 엔드포인트에 대한 설명을 생성(
introspectComments
가true
로 설정된 경우). - 설명을 기반으로 속성에 대한 예제 값을 생성(
introspectComments
가true
로 설정된 경우).
파일명은 반드시 .dto.ts
이거나 .entity.ts
여야 한다.
mappte-types 의 utilies 를 사용하는 경우 (ex - PartialType) @nestjs/mapped-type 대신 @nestjs/swagger 에서 가져와야 한다.
temp.dto.ts
export class Temp {
/**
* The name of Temp
* @example 'Jule'
*/
@IsAlphanumeric()
@MaxLength(8)
name: string;
/**
* The age of Temp
* @example 42
*/
@IsNumber()
@Max(130)
@Min(0)
age: number;
}
- 인식한 dto 를 swagger 에서 확인할 수 있다.
- api 예시에도 설정한 값이 다 들어가 있다.
plugin 사용
plugin 을 사용하려면 nest-cli.json
을 편집한다.
"compilerOptions": {
...
"plugins": [
{
"name": "@nestjs/swagger/plugin",
"options": {
"classValidatorShim": true,
"introspectComments": true
}
}
]
}
추가 설정할 Decorators
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea
docs.nestjs.com
문서에 있는 많은 decorator 들을 살펴보면서 적절하게 값을 주면 된다.
특히 @ApiTags()
는 각 컨트롤러 위에 달아서 태그별로 분리하면 좋을 것 같다!
Reference
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea
docs.nestjs.com
GitHub - nestjs/swagger: OpenAPI (Swagger) module for Nest framework (node.js)
GitHub - nestjs/swagger: OpenAPI (Swagger) module for Nest framework (node.js) :earth_americas:
OpenAPI (Swagger) module for Nest framework (node.js) :earth_americas: - GitHub - nestjs/swagger: OpenAPI (Swagger) module for Nest framework (node.js) :earth_americas:
github.com