diff --git a/kiota-compatibility-guidelines.md b/kiota-compatibility-guidelines.md new file mode 100644 index 0000000..d217b93 --- /dev/null +++ b/kiota-compatibility-guidelines.md @@ -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. + +--- diff --git a/src/app.controller.ts b/src/app.controller.ts index 6cba703..ab57495 100644 --- a/src/app.controller.ts +++ b/src/app.controller.ts @@ -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(); } diff --git a/src/modules/account/account.controller.ts b/src/modules/account/account.controller.ts index 4a60f29..7ce6849 100644 --- a/src/modules/account/account.controller.ts +++ b/src/modules/account/account.controller.ts @@ -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): 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(); } diff --git a/src/modules/image/image.controller.ts b/src/modules/image/image.controller.ts index cc76795..edc1012 100644 --- a/src/modules/image/image.controller.ts +++ b/src/modules/image/image.controller.ts @@ -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) } diff --git a/src/modules/page/page.controller.ts b/src/modules/page/page.controller.ts index 89f55b5..abfa924 100644 --- a/src/modules/page/page.controller.ts +++ b/src/modules/page/page.controller.ts @@ -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, @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 { + @ApiBadRequestResponse({ description: 'pageId λ˜λŠ” spaceId 쀑 ν•˜λ‚˜λŠ” ν•„μˆ˜', type: ErrorResponseDto }) + @ApiNotFoundResponse({ description: 'νŽ˜μ΄μ§€ λ˜λŠ” 슀페이슀λ₯Ό 찾을 수 μ—†μŒ', type: ErrorResponseDto }) + async getPage(@Query() query: GetPageQuery): Promise { 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, @@ -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, @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, @ExtractUserPayloadFromToken() user: EntraIDPayloadClaims diff --git a/src/modules/page/page.service.ts b/src/modules/page/page.service.ts index 8c9f69a..24d1edd 100644 --- a/src/modules/page/page.service.ts +++ b/src/modules/page/page.service.ts @@ -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 { 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'); }