공식 페이지
1. Swagger 설치
npm install --save @nestjs/swagger swagger-ui-express
2. main.ts 복사 및 붙여넣기
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('API 문서 제목')
.setDescription('API 문서 설명')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document);
await app.listen(3000);
}
bootstrap();
3. main.ts에 타이틀 등 추가하고 새로고침하면서 확인
4. 엔티티나 DTO(회원가입, 로그인) 쪽에 @ApiProperty() 추가해야 함
엔티티보다는 DTO에 @ApiProperty() 데코레이터를 적용하는 것이 일반적입니다.
**DTO(Data Transfer Object)**는 클라이언트와 서버 간의 데이터 전송을 위한 클래스이므로,
Swagger 문서화를 위해 DTO에 데코레이터를 추가하는 것이 적절합니다.
import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ description: '유저 이메일', example: 'example@example.com' })
email: string;
@ApiProperty({ description: '유저 비밀번호', example: 'password123' })
password: string;
}
5. 여기서 설명이랑 예를 넣을 수 있음.
import { ApiProperty } from '@nestjs/swagger';
export class UserDto {
@ApiProperty({ description: '유저 이메일', example: 'example@example.com' })
email: string;
}
6. @ApiOperation() 데코레이터를 사용하여 엔드포인트의 설명을 추가합니다.
import { Controller, Post, Body } from '@nestjs/common';
import { ApiOperation } from '@nestjs/swagger';
@Controller('auth')
export class AuthController {
@Post('signup')
@ApiOperation({ summary: '회원가입' })
signup(@Body() createUserDto: CreateUserDto) {
// 회원가입 로직
}
}
8. 인증 관련 전체를 묶고 싶으면 @Controller 머리 위에 @ApiTags('인증') 이렇게 넣으면 됨
import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('인증')
@Controller('auth')
export class AuthController {
// 엔드포인트들
}
요약
Swagger 설치
main.ts에 Swagger 설정 추가
main.ts에서 DocumentBuilder를 사용하여 API 정보 설정
DTO에 @ApiProperty() 데코레이터 추가
TypeScript 컴파일러 옵션 설정 (tsconfig.json)
컨트롤러에서 @ApiOperation() 등을 사용하여 메서드 설명 추가
컨트롤러에 @ApiTags()로 그룹화
인증 main.ts에 .addBearerAuth() 추가 개별 추가 원할시 객체 안에 .
컨트롤러에 @ApiBearerAuth() ,@UseGuards(AuthGuard('jwt')) 추가
아래는 정리 한 부분입니다.
1.1. API 그룹화
@ApiTags('보드')
@Controller('boards')
export class BoardsController { /* ... */ }
1.2. 요청 및 응답 모델 문서화
export class CreateBoardDto {
@ApiProperty({ description: '보드 제목', example: '프로젝트 계획' })
title: string;
@ApiProperty({ description: '보드 설명', example: '프로젝트에 대한 상세 계획을 담은 보드입니다.' })
description: string;
}
1.3. 엔드포인트 설명 및 응답 정의
@Post()
@ApiOperation({ summary: '보드 생성' })
@ApiResponse({ status: 201, description: '보드가 성공적으로 생성됨', type: BoardDto })
createBoard(@Body() createBoardDto: CreateBoardDto) {
// 보드 생성 로직
}
1.4. 인증 및 권한 설정
@ApiBearerAuth()
@UseGuards(AuthGuard('jwt'))
@Put(':id')
updateBoard(@Param('id') id: string, @Body() updateBoardDto: UpdateBoardDto) {
// 보드 업데이트 로직
}
1.5. 쿼리 및 경로 파라미터 문서화
@Get(':id')
@ApiParam({ name: 'id', description: '보드 ID', example: '123' })
getBoard(@Param('id') id: string) {
// 보드 조회 로직
}
아래는 우리 트렐로 프로젝트의 예 입니다.
2.1.1. 카드 생성
@ApiTags('카드')
@ApiBearerAuth()
@Controller('cards')
export class CardsController {
@Post()
@ApiOperation({ summary: '카드 생성' })
@ApiResponse({ status: 201, description: '카드가 성공적으로 생성됨', type: CardDto })
@UseGuards(AuthGuard('jwt'))
createCard(@Body() createCardDto: CreateCardDto) {
// 카드 생성 로직
}
}
2.2.1. 리스트 조회
@ApiTags('리스트')
@Controller('lists')
export class ListsController {
@Get()
@ApiOperation({ summary: '리스트 조회' })
@ApiResponse({ status: 200, description: '리스트 목록 반환', type: [ListDto] })
getLists() {
// 리스트 조회 로직
}
}
추후에 쓸 파일 업로드는
**@ApiConsumes()**와 **@ApiBody()**를 사용하여 파일 업로드 엔드포인트를 문서화합니다
@Post('upload')
@ApiConsumes('multipart/form-data')
@ApiBody({
description: '이미지 파일 업로드',
type: FileUploadDto,
})
uploadFile(@UploadedFile() file: Express.Multer.File) {
// 파일 업로드 로직
}
그리고 우리 프로젝트에 이넘은 아직 없지만 이넘을 쓸때는
2.3 이넘값
export enum CardStatus {
TODO = 'TODO',
IN_PROGRESS = 'IN_PROGRESS',
DONE = 'DONE',
}
export class UpdateCardDto {
@ApiProperty({ enum: CardStatus, description: '카드 상태', example: CardStatus.IN_PROGRESS })
status: CardStatus;
}
'Daily Logs > TIL (Today I Learned)' 카테고리의 다른 글
Private 를 모킹 해야하나 말아야하나 ?? ,1. { user: { id: mockUser.id } }가 필요한 이유 (1) | 2024.11.29 |
---|---|
JavaScript deep dive 변수 선언의 실행 시점과 변수 호이스팅 (0) | 2024.11.27 |
와이어 프레임의 중요성 (1) | 2024.10.21 |
아키텍쳐 패턴 코드 수정 history (1) | 2024.10.13 |
메모리(Memory)란 ? (1) | 2024.10.08 |