$ npm install --save @nestjs/swagger
핵심적으로 구현되어야 하는 데코레이터는 다음과 같다
// controller 분기
@ApiTags('users')
@ApiOperation({ summary: 요약, description: 세부 정보 })
@ApiResponse({ status: 404, description: 세부 정보 })
ApiBody
ApiParam
ApiQuery
endpoint 에 대한 정보를 제공한다. summary
, description
뿐만 아니라 tags
를 사용해서 추가적인 분류도 가능하다
@ApiOperation({
summary: 'Get all items',
description: 'Get a list of all items',
tags: ['Lists']
})
처리 값에 대한 결과값을 반환한다
@ApiResponse({ status: 200, description: 'User found', type: UserEntity })
@ApiResponse({ status: 404, description: 'User not found' })
여기서, status code 가 중복되는 것을 방지하기 위해서 다양한 종류의 custom response 들이 존재한다. 아래와 같이 response 를 두가지 방법으로 정의 할 수 있다.
@ApiResponse({ status: 404, description: 'User not found' })
@ApiNotFoundResponse({ description: 'User not found' })
- ApiResponse
- [200] @ApiCreatedResponse({ description: 'User created', type: UserEntity })
`새로운 리소스를 생성하는 엔드포인트에서 반환되는 HTTP 응답(response)에 대한 설명을 추가하기 위해 사용된다.
주로 POST 요청에 대한 응답을 문서화하고 설명할 때 사용된다.`
- [404] @ApiNotFoundResponse({ description: 'User not found' })
예시를 한번 보도록 하자
@Controller('v1/users')
@ApiTags('유저 API')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post()
@ApiOperation({ summary: '유저 생성 API', description: '유저를 생성한다.' })
@ApiCreatedResponse({ description: '유저를 생성한다.', type: User })
async create(@Body() requestDto: UserCreateRequestDto, @Res() res: Response) {
const user: User = await this.userService.createUser(requestDto);
return res.status(HttpStatus.CREATED).json(user);
}
}
@ApiProperty()
`이 데코레이터를 사용하여 DTO의 각 속성(property)을 문서화합니다.
속성의 이름, 설명, 타입 등을 정의할 수 있습니다.`
@ApiPropertyOptional()
`선택적으로 사용 가능한 속성을 문서화할 때 사용합니다.
이 데코레이터를 사용하면 해당 속성이 필수가 아님을 나타낼 수 있습니다.`
@ApiProperty({ enum: YourEnum })
`Enum 값을 문서화하기 위해 사용됩니다. Enum 값의 설명과 함께 Enum 타입을 문서화할 수 있습니다.`
@ApiProperty({ type: YourType })
`객체나 배열과 같은 복잡한 타입을 문서화할 때 사용합니다. 해당 타입의 구조를 설명할 수 있습니다.`
@ApiHideProperty()
`문서에 특정 속성을 표시하지 않고 숨길 때 사용합니다.
예를 들어 비밀번호와 같은 민감한 정보를 문서에 노출하지 않을 때 유용합니다.`
@ApiExtraModels()
`DTO 내에서 사용되는 추가 모델을 선언할 때 사용됩니다.
이는 DTO 안에서 사용되는 객체나 클래스를 별도의 모델로 정의하고 문서화할 때 유용합니다.`
// string array
@ApiProperty({ type: String, isArray: true })
@ApiProperty({ type: [String] })
@ApiProperty({
name: string, // 속성의 이름
description?: string, // 속성에 대한 설명
required?: boolean, // 속성이 필수인지 여부 (기본값: true)
isArray?: boolean, // 속성이 배열인지 여부
enum?: any[], // 열거형 값의 유효한 값 목록
enumName?: string, // 열거형 값의 이름
default?: any, // 속성의 기본 값
type?: any, // 속성의 타입 (TypeScript 타입 또는 클래스)
isArray?: boolean, // 속성이 배열인지 여부
collectionFormat?: string, // 배열의 컬렉션 형식 (csv, ssv, tsv, pipes)
format?: string, // 속성의 형식 (email, date, uuid 등)
minimum?: number, // 속성의 최소 값
maximum?: number, // 속성의 최대 값
minLength?: number, // 문자열 속성의 최소 길이
maxLength?: number, // 문자열 속성의 최대 길이
multipleOf?: number, // 숫자의 배수 값
pattern?: string, // 정규식 패턴
example?: any, // 속성의 예시 값
nullable?: boolean, // 속성이 null일 수 있는지 여부
})
https://docs.nestjs.com/openapi/types-and-parameters
https://docs.nestjs.com/openapi/cli-plugin
@ApiImplicitFile({ name: 'file', required: true, description: 'List of cats' })
uploadFile(@UploadedFile() file) {}
https://jakekwak.gitbook.io/nestjs/recipes/untitled-4#file-upload