Swagger(스웨거)는 개발자가 REST 웹 서비스를 설계, 빌드, 문서화, 소비하는 일을 도와주는 대형 도구 생태계의 지원을 받는 오픈 소스 소프트웨어 프레임워크이다. 대부분의 사용자들은 Swagger UI 도구를 통해 스웨거를 식별하며 툴셋에는 자동화된 문서화, 코드 생성, 테스트 케이스 생성 지원이 포함된다. - wikipedia

 

 

NPM 패키지 설치

$ npm install --save @nestjs/swagger

 

 

src/config/swagger.config.ts

import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger"

export default app => {
    const config = new DocumentBuilder()
        .setTitle('nest project')
        .setDescription('description')
        .setVersion('1.0.0')
        .build();

    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('swagger', app, document);
}
  • http://localhost:3000/swaggerSwagger UI 접속

 

 

DocumentBuilder Options

더보기
import { OpenAPIObject } from './interfaces';
import { ExternalDocumentationObject, ParameterObject, SecurityRequirementObject, SecuritySchemeObject, ServerVariableObject } from './interfaces/open-api-spec.interface';
export declare class DocumentBuilder {
    private readonly logger;
    private readonly document;
    setTitle(title: string): this;
    setDescription(description: string): this;
    setVersion(version: string): this;
    setTermsOfService(termsOfService: string): this;
    setContact(name: string, url: string, email: string): this;
    setLicense(name: string, url: string): this;
    addServer(url: string, description?: string, variables?: Record<string, ServerVariableObject>): this;
    setExternalDoc(description: string, url: string): this;
    setBasePath(path: string): this;
    addTag(name: string, description?: string, externalDocs?: ExternalDocumentationObject): this;
    addSecurity(name: string, options: SecuritySchemeObject): this;
    addGlobalParameters(...parameters: ParameterObject[]): this;
    addSecurityRequirements(name: string | SecurityRequirementObject, requirements?: string[]): this;
    addBearerAuth(options?: SecuritySchemeObject, name?: string): this;
    addOAuth2(options?: SecuritySchemeObject, name?: string): this;
    addApiKey(options?: SecuritySchemeObject, name?: string): this;
    addBasicAuth(options?: SecuritySchemeObject, name?: string): this;
    addCookieAuth(cookieName?: string, options?: SecuritySchemeObject, securityName?: string): this;
    build(): Omit<OpenAPIObject, 'paths'>;
}

 

 

SwaggerModule.setup의 첫번째 매개변수는 swagger path를 의미

 

 

src/main.ts

	...
import swagger from './config/swagger.config';

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

	...

  swagger(app);

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

 

 

src/app/app.controller.ts  →  @ApiTags. @ApiOperation. @ApiOkResponse. @ApiBadRequestResponse

	...

@ApiTags('app tag')
@Controller()
export class AppController {

  constructor(private readonly appService: AppService) { }

  @ApiOperation({
    summary: '서버 상태 검사',
    description: '정상적으로 서버가 실행되고 있는지 확인'
  })
  @ApiOkResponse({
    description: 'OK'
  })
  @ApiBadRequestResponse({
    description: 'Bad Request'
  })
  @Head()
  getStatus() {
    this.appService.getStatus();
  }
  
  	...

 

 

swagger ui 확인

 

 

 


참고 링크

https://docs.nestjs.com/openapi/introduction

https://any-ting.tistory.com/122

https://www.npmjs.com/package/@nestjs/swagger

'JavaScript > NestJS' 카테고리의 다른 글

[NestJS] Guard + JWT 구현하기  (0) 2023.08.27
[NestJS] Exception filters  (0) 2023.08.21
[NestJS] TypeORM CRUD 생성하기 (User)  (0) 2023.08.21
[NestJS] 환경 변수 (config) 사용하기  (0) 2023.08.20
[NestJS] Logging 하기  (0) 2023.08.19

+ Recent posts