NestJS를 사용한 자바스크립트 앱의 API 문서화 방법

NestJS는 JavaScript 및 TypeScript를 위한 프레임워크로, 서버 사이드 애플리케이션의 개발을 단순하고 효율적으로 만들어줍니다. API 문서화는 애플리케이션의 개발 프로세스 중에서도 매우 중요한 부분입니다. 이 문서에서는 NestJS 애플리케이션의 API를 문서화하는 방법에 대해 알아보겠습니다.

1. Swagger

Swagger는 API 문서화 도구로 널리 사용되며, NestJS에서도 Swagger를 통해 API를 문서화할 수 있습니다. NestJS는 @nestjs/swagger 모듈을 통해 Swagger와의 통합을 지원합니다.

먼저, NestJS 프로젝트에 @nestjs/swagger 모듈을 설치합니다.

$ npm install --save @nestjs/swagger swagger-ui-express

그런 다음, main.ts 파일에서 다음과 같이 설정합니다.

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Swagger 설정
  const config = new DocumentBuilder()
    .setTitle('API 문서')
    .setDescription('API 문서입니다.')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  await app.listen(3000);
}
bootstrap();

이제 API 문서를 생성하고 싶은 컨트롤러 클래스에 @ApiTags, @ApiOperation, @ApiResponse 어노테이션을 사용하여 각 요청에 대한 설명을 추가할 수 있습니다.

import { Controller, Get } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';

@Controller('users')
@ApiTags('users')
export class UserController {
  @Get()
  @ApiOperation({ summary: '모든 사용자 조회' })
  @ApiResponse({ status: 200, description: '성공', type: [User] })
  @ApiResponse({ status: 500, description: '서버 에러' })
  async findAll(): Promise<User[]> {
    return await this.userService.findAll();
  }
}

이제 애플리케이션을 실행하고 http://localhost:3000/api로 접속하면 Swagger UI를 통해 문서화된 API를 확인할 수 있습니다.

2. TypeDoc

TypeDoc은 TypeScript를 사용하는 프로젝트의 API를 문서화하는 도구입니다. NestJS 애플리케이션은 TypeScript로 개발되기 때문에 TypeDoc을 사용하여 API를 문서화할 수 있습니다.

먼저, TypeDoc을 설치합니다.

$ npm install --save-dev typedoc

그리고 프로젝트의 루트 디렉토리에 typedoc.json 파일을 생성하고 다음과 같이 설정합니다.

{
  "name": "My Project",
  "out": "./docs",
  "entryPoints": ["src"],
  "includeDeclarations": true,
  "excludeExternals": true,
  "excludePrivate": true,
  "excludeProtected": true,
  "excludeNotExported": true
}

이제 다음 명령어를 실행하여 API 문서를 생성할 수 있습니다.

$ typedoc

위의 명령을 실행하면 ./docs 디렉토리에 HTML 형식으로 문서가 생성됩니다. 생성된 문서를 브라우저에서 열어 확인할 수 있습니다.

결론

NestJS 애플리케이션의 API 문서화는 개발자들이 애플리케이션의 기능과 사용 방법을 이해하고 효과적으로 사용할 수 있도록 도와줍니다. 위에서 소개한 Swagger와 TypeDoc을 사용하여 API를 문서화할 수 있으며, 개발자들에게 편리한 참고 자료를 제공할 수 있습니다.

#NestJS #API문서화