Enhances Swagger API documentation and response consistency

Adds comprehensive Swagger decorators across App, Account, and Image controllers to improve API endpoint clarity and detail. This includes adding API tags, operation summaries, response types, authentication requirements, and specific schema for file uploads.

Standardizes error responses within the Page module by introducing a consistent `ErrorResponseDto` for bad requests, not found errors, and unauthorized access. Also refactors the `getPage` endpoint to return a `PageListResponseDto`, ensuring uniform list responses.

Updates DTO definitions in `page.service.ts` with explicit types and nullability for improved accuracy in generated documentation.
This commit is contained in:
dahyeon committed 2025-11-11 17:14:14 +00:00
1 parent de24f0dd3f
commit 815d44c161
6 files changed
+272 -49

No files matched your search

+185
View File
@@ -0,0 +1,185 @@
Here’s a concise **English version** of the essential Kiota-compatibility guidelines, suitable for giving to another AI agent or automated generator:
---
## 🧩 **Kiota Compatibility Guidelines for NestJS Swagger APIs**
**Goal:** Ensure the OpenAPI spec generated by NestJS Swagger can be fully parsed by Kiota without losing endpoints or models.
---
### ✅ 1. OpenAPI Version
* Use **OpenAPI 3.0.x** (Kiota doesn’t support 3.1).
* Avoid non-standard or experimental extensions.
---
### ✅ 2. Request & Response Schemas
* Always define a **schema** for every request and 2XX response.
* Use `application/json` as the single content type.
* Avoid multiple response formats per endpoint.
* Empty 204 responses → no `type`, only `description`.
* **CRITICAL**: Always explicitly specify `type` in `@ApiProperty` for all DTO fields, especially when using `nullable: true` or `format`.
```typescript
// ❌ BAD - Kiota warns about format on nullable types
@ApiProperty({ format: 'uuid', nullable: true })
id?: string;
// ✅ GOOD - Explicitly specify type
@ApiProperty({ type: String, format: 'uuid', nullable: true })
id?: string;
```
---
### ✅ 3. Error Handling
* Define object-type **error schemas** for 4XX/5XX responses.
* Avoid array-type root errors (`[{message}]` → `{ errors: [...] }`).
* Kiota maps errors to typed exceptions only if schema exists.
* **CRITICAL**: Every endpoint must have `@ApiResponse` decorators, even if it just returns a simple string.
```typescript
// ❌ BAD - No Swagger decorators
@Get()
healthCheck(): string {
return 'OK';
}
// ✅ GOOD - Has response decorator
@Get()
@ApiOperation({ summary: 'Health check' })
@ApiResponse({ status: 200, description: 'Server is healthy', type: String })
healthCheck(): string {
return 'OK';
}
```
---
### ✅ 4. Models & Polymorphism
* Use **`allOf` + `discriminator`** for inheritance.
* Avoid `oneOf`/`anyOf` unless you add a `discriminator` and reference named components.
* Never use anonymous inline schemas or `type: any`.
* **CRITICAL**: For endpoints that can return different response shapes, create a wrapper DTO instead of using `oneOf`.
```typescript
// ❌ BAD - oneOf without discriminator
@ApiResponse({
schema: {
oneOf: [
{ $ref: '#/components/schemas/PageDto' },
{ type: 'array', items: { $ref: '#/components/schemas/PageDto' } }
]
}
})
// ✅ GOOD - Consistent wrapper type
export class PageListResponseDto {
@ApiProperty({ type: [PageDto] })
pages: PageDto[];
}
@ApiResponse({ type: PageListResponseDto })
```
---
### ✅ 5. Query & Header Parameters
* Define query params individually (`@ApiQuery` per field).
* Avoid `deepObject` style; use simple `form` style.
* Enums in queries become **strings** in Kiota.
* Kiota does **not** auto-generate custom header fields — document required headers.
---
### ✅ 6. Authentication
* Use standard `Bearer`, `OAuth2`, or `openIdConnect` security schemes.
* Include `openIdConnectUrl` or token endpoint if applicable.
* Apply `@ApiBearerAuth()` on secured endpoints.
---
### ✅ 7. File Uploads
* Prefer JSON metadata + binary file upload separately.
* If multipart is required, use Kiota form-serialization packages (`@microsoft/kiota-serialization-form`).
* Always use `@ApiConsumes('multipart/form-data')` and define proper `@ApiBody` schema:
```typescript
@Post()
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
properties: {
file: { type: 'string', format: 'binary' }
}
}
})
@ApiResponse({ status: 201, type: UploadResultDto })
uploadFile(@UploadedFile() file: Express.Multer.File) {
// ...
}
```
---
### ✅ 8. Validation & Generation
* Check for Kiota CLI warnings (`kiota generate --log-level info`).
* Verify all endpoints produce request builders.
* Re-generate after Swagger or Kiota updates.
---
## 🔧 **Common Kiota Warnings & Solutions**
### Warning: "The format X is not supported by Kiota for the type Object"
**Cause:** Using `format` (uuid, date-time) on nullable types without explicitly specifying `type`.
**Solution:** Always add `type: String` (or appropriate type) to `@ApiProperty`:
```typescript
// Before
@ApiProperty({ format: 'uuid', nullable: true })
parentId?: string;
// After
@ApiProperty({ type: String, format: 'uuid', nullable: true })
parentId?: string;
```
### Warning: "Could not create error type for 4XX/5XX in [EndpointName]"
**Cause:** Missing Swagger decorators on endpoints.
**Solution:** Add `@ApiOperation`, `@ApiResponse`, and `@ApiTags` to all endpoints:
```typescript
@ApiTags('MyController')
@Controller('my-route')
export class MyController {
@Get()
@ApiOperation({ summary: 'Get data' })
@ApiResponse({ status: 200, type: MyDto })
getData() { /* ... */ }
}
```
### Warning: "oneOf/anyOf without discriminator"
**Cause:** Using `oneOf` in response schemas without a discriminator field.
**Solution:** Create a wrapper DTO with a consistent structure:
```typescript
// Instead of returning PageDto | PageDto[]
// Always return PageListDto { pages: PageDto[] }
```
---
**Outcome:** Following these rules ensures every NestJS API route and model is fully generated by Kiota's TypeScript client without loss of fidelity.
---
+4
View File
@@ -1,8 +1,10 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { AppService } from './app.service';
import { JwtAuthGuard } from './modules/global/auth/jwt.guard';
import { AllowPublicAccess } from './modules/global/auth/allow-public-access.decorator';
@ApiTags('Health')
@UseGuards(JwtAuthGuard)
@Controller()
export class AppController {
@@ -10,6 +12,8 @@ export class AppController {
@AllowPublicAccess()
@Get()
@ApiOperation({ summary: 'Health check', description: '서버 상태 확인' })
@ApiResponse({ status: 200, description: '서버 정상', type: String })
isHealthy(): string {
return this.appService.isHealthy();
}
@@ -1,16 +1,21 @@
import { Controller, Get, UseGuards } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from "@nestjs/swagger";
import { AccountService } from "./account.service";
import { JwtAuthGuard } from "../global/auth/jwt.guard";
import { AllowPublicAccess } from "../global/auth/allow-public-access.decorator";
import { ExtractUserPayloadFromToken } from "../global/auth/extract-user-payload-from-token.decorator";
import { EntraIDPayloadClaims } from "../global/auth/jwt.service";
@ApiTags('Account')
@Controller('account')
export class AccountController {
constructor(private readonly accountService: AccountService) {}
@Get('signin')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '로그인', description: '사용자 로그인' })
@ApiResponse({ status: 200, description: '로그인 성공', type: String })
signIn(@ExtractUserPayloadFromToken() userPayload: Omit<EntraIDPayloadClaims, 'iss' | 'iat' | 'nbf' | 'rh' | 'ver'>): string {
return this.accountService.signIn('test', userPayload);
}
@@ -18,6 +23,9 @@ export class AccountController {
@Get()
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '계정 정보 조회', description: '현재 로그인한 사용자의 계정 정보 조회' })
@ApiResponse({ status: 200, description: '계정 정보 조회 성공', type: String })
getAccountInfo(): string {
return this.accountService.getAccountInfo();
}
+16
View File
@@ -1,13 +1,29 @@
import { Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiConsumes, ApiBody } from '@nestjs/swagger';
import { ImageService } from './image.service';
import { FileInterceptor } from '@nestjs/platform-express';
@ApiTags('Image')
@Controller('image')
export class ImageController {
constructor(private readonly imageService: ImageService) {}
@Post()
@UseInterceptors(FileInterceptor('file'))
@ApiOperation({ summary: '이미지 업로드', description: '이미지 파일을 업로드합니다' })
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
properties: {
file: {
type: 'string',
format: 'binary',
},
},
},
})
@ApiResponse({ status: 201, description: '이미지 업로드 성공', type: String })
async uploadImage(@UploadedFile() file: Express.Multer.File) {
return this.imageService.uploadImage(file)
}
+20 -26
View File
@@ -21,7 +21,9 @@ import {
DeleteTokenDto,
PageResponseDto,
CreateTokenResponseDto,
DeleteResponseDto
DeleteResponseDto,
ErrorResponseDto,
PageListResponseDto
} from "./page.service";
import { AllowPublicAccess } from "../global/auth/allow-public-access.decorator";
import { ExtractUserPayloadFromToken } from "../global/auth/extract-user-payload-from-token.decorator";
@@ -87,9 +89,9 @@ export class PageController {
description: '페이지가 성공적으로 생성됨',
type: PageResponseDto
})
@ApiBadRequestResponse({ description: '잘못된 요청 (부모 페이지가 다른 스페이스에 있음 등)' })
@ApiNotFoundResponse({ description: '스페이스 또는 부모 페이지를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
@ApiBadRequestResponse({ description: '잘못된 요청 (부모 페이지가 다른 스페이스에 있음 등)', type: ErrorResponseDto })
@ApiNotFoundResponse({ description: '스페이스 또는 부모 페이지를 찾을 수 없음', type: ErrorResponseDto })
@ApiUnauthorizedResponse({ description: '인증 실패', type: ErrorResponseDto })
async createPage(
@Body() dto: Omit<CreatePageDto, 'userId'>,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
@@ -127,19 +129,11 @@ export class PageController {
@ApiResponse({
status: 200,
description: '페이지 조회 성공',
schema: {
oneOf: [
{ $ref: '#/components/schemas/PageResponseDto' },
{
type: 'array',
items: { $ref: '#/components/schemas/PageResponseDto' }
}
]
}
type: PageListResponseDto
})
@ApiBadRequestResponse({ description: 'pageId 또는 spaceId 중 하나는 필수' })
@ApiNotFoundResponse({ description: '페이지 또는 스페이스를 찾을 수 없음' })
async getPage(@Query() query: GetPageQuery): Promise<PageResponseDto | PageResponseDto[]> {
@ApiBadRequestResponse({ description: 'pageId 또는 spaceId 중 하나는 필수', type: ErrorResponseDto })
@ApiNotFoundResponse({ description: '페이지 또는 스페이스를 찾을 수 없음', type: ErrorResponseDto })
async getPage(@Query() query: GetPageQuery): Promise<PageListResponseDto> {
return await this.pageService.getPage(query) as any;
}
@@ -194,9 +188,9 @@ export class PageController {
description: '페이지가 성공적으로 업데이트됨',
type: PageResponseDto
})
@ApiBadRequestResponse({ description: '잘못된 요청 (순환 참조, 자기 자신을 부모로 설정 등)' })
@ApiNotFoundResponse({ description: '페이지 또는 부모 페이지를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
@ApiBadRequestResponse({ description: '잘못된 요청 (순환 참조, 자기 자신을 부모로 설정 등)', type: ErrorResponseDto })
@ApiNotFoundResponse({ description: '페이지 또는 부모 페이지를 찾을 수 없음', type: ErrorResponseDto })
@ApiUnauthorizedResponse({ description: '인증 실패', type: ErrorResponseDto })
async updatePage(
@Param('pageId') pageId: string,
@Body() dto: Omit<UpdatePageDto, 'userId'>,
@@ -229,8 +223,8 @@ export class PageController {
description: '페이지가 성공적으로 삭제됨',
type: DeleteResponseDto
})
@ApiNotFoundResponse({ description: '페이지를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
@ApiNotFoundResponse({ description: '페이지를 찾을 수 없음', type: ErrorResponseDto })
@ApiUnauthorizedResponse({ description: '인증 실패', type: ErrorResponseDto })
async deletePage(
@Param('pageId') pageId: string,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
@@ -290,9 +284,9 @@ export class PageController {
description: '토큰이 성공적으로 생성됨',
type: CreateTokenResponseDto
})
@ApiBadRequestResponse({ description: 'pageIds 또는 spaceIds 중 최소 하나는 필수' })
@ApiNotFoundResponse({ description: '페이지 또는 스페이스를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
@ApiBadRequestResponse({ description: 'pageIds 또는 spaceIds 중 최소 하나는 필수', type: ErrorResponseDto })
@ApiNotFoundResponse({ description: '페이지 또는 스페이스를 찾을 수 없음', type: ErrorResponseDto })
@ApiUnauthorizedResponse({ description: '인증 실패', type: ErrorResponseDto })
async createTemporaryAccessToken(
@Body() dto: Omit<CreateTemporaryTokenDto, 'userId'>,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
@@ -332,8 +326,8 @@ export class PageController {
description: '토큰이 성공적으로 삭제됨',
type: DeleteResponseDto
})
@ApiNotFoundResponse({ description: '토큰을 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패 또는 토큰 생성자만 삭제 가능' })
@ApiNotFoundResponse({ description: '토큰을 찾을 수 없음', type: ErrorResponseDto })
@ApiUnauthorizedResponse({ description: '인증 실패 또는 토큰 생성자만 삭제 가능', type: ErrorResponseDto })
async deleteTemporaryAccessToken(
@Body() dto: Omit<DeleteTokenDto, 'userId'>,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
+39 -23
View File
@@ -162,54 +162,54 @@ export class DeleteTokenDto {
}
export class PageResponseDto {
@ApiProperty({ description: '페이지 ID', format: 'uuid' })
@ApiProperty({ description: '페이지 ID', type: String, format: 'uuid' })
pageId: string;
@ApiProperty({ description: '스페이스 ID', format: 'uuid' })
@ApiProperty({ description: '스페이스 ID', type: String, format: 'uuid' })
spaceId: string;
@ApiProperty({ description: '부모 페이지 ID', format: 'uuid', nullable: true })
@ApiProperty({ description: '부모 페이지 ID', type: String, format: 'uuid', nullable: true })
parentPageId: string | null;
@ApiProperty({ description: '정렬 순서' })
sortOrder: number;
@ApiProperty({ description: '정렬 순서', type: Number, nullable: true })
sortOrder: number | null;
@ApiProperty({ description: '페이지 제목' })
@ApiProperty({ description: '페이지 제목', type: String })
title: string;
@ApiProperty({ description: '페이지 내용', nullable: true })
@ApiProperty({ description: '페이지 내용', type: String, nullable: true })
content: string | null;
@ApiProperty({ description: '생성자 사용자 ID', format: 'uuid' })
@ApiProperty({ description: '생성자 사용자 ID', type: String, format: 'uuid' })
createdByUserId: string;
@ApiProperty({ description: '수정자 사용자 ID', format: 'uuid' })
@ApiProperty({ description: '수정자 사용자 ID', type: String, format: 'uuid' })
updatedByUserId: string;
@ApiProperty({ description: '생성 시간', format: 'date-time' })
createdAt: string;
@ApiProperty({ description: '생성 시간', type: String, format: 'date-time', nullable: true })
createdAt: string | null;
@ApiProperty({ description: '수정 시간', format: 'date-time' })
updatedAt: string;
@ApiProperty({ description: '수정 시간', type: String, format: 'date-time', nullable: true })
updatedAt: string | null;
@ApiProperty({ description: '삭제 여부' })
isDeleted: boolean;
@ApiProperty({ description: '삭제 여부', type: Boolean, nullable: true })
isDeleted: boolean | null;
}
export class TokenInfoDto {
@ApiProperty({ description: '토큰 ID', format: 'uuid' })
@ApiProperty({ description: '토큰 ID', type: String, format: 'uuid' })
tokenId: string;
@ApiProperty({ description: '토큰 값 (실제 사용할 토큰 문자열)' })
@ApiProperty({ description: '토큰 값 (실제 사용할 토큰 문자열)', type: String })
tokenValue: string;
@ApiProperty({ description: '토큰 설명', nullable: true })
@ApiProperty({ description: '토큰 설명', type: String, nullable: true })
description: string | null;
@ApiProperty({ description: '만료 시간', format: 'date-time', nullable: true })
@ApiProperty({ description: '만료 시간', type: String, format: 'date-time', nullable: true })
expiresAt: string | null;
@ApiProperty({ description: '생성 시간', format: 'date-time' })
@ApiProperty({ description: '생성 시간', type: String, format: 'date-time' })
createdAt: string;
}
@@ -240,6 +240,22 @@ export class DeleteResponseDto {
tokenId?: string;
}
export class ErrorResponseDto {
@ApiProperty({ description: '에러 메시지' })
message: string;
@ApiProperty({ description: 'HTTP 상태 코드' })
statusCode: number;
@ApiPropertyOptional({ description: '에러 상세 정보' })
error?: string;
}
export class PageListResponseDto {
@ApiProperty({ description: '페이지 목록', type: [PageResponseDto] })
pages: PageResponseDto[];
}
@Injectable()
export class PageService {
constructor(
@@ -286,14 +302,14 @@ export class PageService {
/**
* 페이지 조회
*/
async getPage(query: GetPageQuery) {
async getPage(query: GetPageQuery): Promise<PageListResponseDto> {
if (query.pageId) {
// 특정 페이지 조회
const page = await this.pageRepository.findById(query.pageId);
if (!page) {
throw new NotFoundException(`Page with id '${query.pageId}' not found`);
}
return [page];
return { pages: [page] };
} else if (query.spaceId) {
// 스페이스의 모든 페이지 조회
const space = await this.spaceRepository.findById(query.spaceId);
@@ -301,7 +317,7 @@ export class PageService {
throw new NotFoundException(`Space with id '${query.spaceId}' not found`);
}
const pages = await this.pageRepository.findBySpaceId(query.spaceId);
return pages;
return { pages };
} else {
throw new BadRequestException('Either pageId or spaceId must be provided');
}