Swagger
Swagger는 REST API를 문서화해주는 라이브러리입니다.
Swagger 환경 설정
패키지 추가
npm install @nestjs/swagger
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 swaggerInfo = new DocumentBuilder()
.setTitle('Cats example') // 앱 이름
.setDescription('The cats API description') // 앱 설명
.setVersion('1.0') // 앱 버전
.setLicense('MIT License', 'https://en.wikipedia.org/wiki/MIT_License') // 저작권 설정
.addServer('naver.com') // 도메인 추가
.addServer('google.com') // 도메인 추가
.build();
// swaggerInfo를 이용해 문서 생성.
const document = SwaggerModule.createDocument(app, swaggerInfo);
// API 확인 웹 페이지 생성. URL은 '도메인/첫번째인자' 형식입니다.
SwaggerModule.setup('api', app, document);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
Swagger 사용 예시
컨트롤러 파일
@ApiTags(태그명) 미지정시 컨트롤러 클래스명이 태그명이 됩니다.
@Controller('User') // 컨트롤러 라우팅 지정 여부와 관계 없이 클래스명을 참조하여 태그 생성
@ApiTags('유저') // 태그 수정
export class UsersController {}
라우팅 메서드
@Get('{/:id}')
// API 설명
@ApiOperation({
summary: '유저 정보 조회',
})
// API 응답 코드 및 설명
@ApiResponse({
status: 200,
description: '유저 정보 반환 시 코드',
})
// name 속성의 값과 일치하는 파라미터의 설명과 예시
@ApiQuery({
name: 'limit',
type: 'number',
required: false, // 필수값 X
description: '페이지 당 최대 반환 개수',
example: 10,
})
@ApiQuery({
name: 'page',
type: 'number',
required: false, // 필수값 X
description: '조회할 페이지',
example: 1,
})
getUsers(
@Param() userDto: UserDto,
@Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
) {
return this.usersService.findAll(userDto, limit, page);
}
DTO 파일
export class UserDto {
// 필수값이 아닌 경우
@ApiPropertyOptional({
description: '유저의 ID',
example: 1234,
})
id?: number;
// 필수값인 경우
@ApiProperty({
description: '유저의 이름'
})
name: string;
}
@ApiProperty(), @ApiPropertyOptional()의 옵션 속성
속성 | 설명 |
description | 설명 |
example | 예시 |
required | 필수값 여부 |
type | 자료형 지정 number, integer, boolean, array, object, string(Date(), 파일 포함) |
enum | enum의 경우 어떤 enum을 참조하는지 명시 |
minumum, maximum | 최소값, 최대값 |
minLength, maxLength | 최소길이, 최대길이 |
default | 기본값 |
array 예시
@ApiProperty({ type: [String] }) // ['string']은 안 됩니다.
names: string[];
enum 예시
@ApiProperty({ enum: UserRole }) // enum: [ 'A', 'B' ]로 대체 가능합니다.
role: UserRole;
object 예시
이미 정의된 객체를 이용할 때
@ApiProperty({
type: Record,
})
rawDefinition: Record;
객체를 직접 정의할 때
@ApiProperty({
type: 'object',
properties: {
name: {
type: 'string',
example: 'Error'
},
status: {
type: 'number',
example: 400
}
},
required: ['name', 'status'] // 개별 속성에 required 사용 가능합니다.
})
rawDefinition: Record;
객체 배열 예시
@ApiProperty({
isArray: true,
type: CreatePostMetaOptionsDto,
})
arrayObject: CreatePostMetaOptionsDto[];
Swagger에서 mapped 타입 사용
@nestjs/mapped-types 패키지의 mapped 타입을 사용하면 API 문서가 정상적으로 생성되지 않습니다.
Swagger 사용 시 @nestjs/swagger 패키지의 mapped 타입을 사용해야 합니다.
또한 원본 DTO의 모든 속성에 @ApiProperty(), @ApiPropertyOptional() 데코레이터를 명시해야 mapped 타입 DTO에서 참조할 수 있습니다.
제공 속성
속성 | 설명 |
PartialType | 기존 DTO의 모든 속성들을 선택적으로 사용 가능한 DTO 생성 |
PickType | 기존 DTO의 속성 중 사용 가능한 일부를 명시한 DTO 생성 |
OmitType | 기존 DTO의 속성 중 사용 불가능한 일부를 명시한 DTO 생성 |
IntersectionType | 두 DTO의 모든 속성을 결합한 DTO 생성 |
사용 예시
기존 DTO
export class CreateUserDto {
@ApiProperty({
description: '사용자 이름',
})
name: string;
@ApiProperty({
description: '사용자 메일',
})
email: string;
@ApiProperty({
description: '사용자 비밀번호',
})
@Matches(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/, {
message: '알파뱃, 숫자, 특수문자를 각각 최소 한 개 이상 입력해주세요.',
})
password: string;
}
PartialType DTO
import { PartialType } from '@nestjs/mapped-swagger';
import { CreateUserDto } from './create-user.dto';
export class PatchUserDto extends PartialType(CreateUserDto) {}
'NestJS > NestJS 레시피' 카테고리의 다른 글
Compodoc (0) | 2025.05.06 |
---|