πŸ“¦ Kimsoo0119 / nest-swagger-builder

πŸ“„ README.ko.md Β· 299 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299# Nest Swagger Builder

[![npm version](https://badge.fury.io/js/nest-swagger-builder.svg)](https://badge.fury.io/js/nest-swagger-builder)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

NestJSμ—μ„œ Swagger λ¬Έμ„œ μž‘μ„±μ„ ν•¨μˆ˜ν˜• μŠ€νƒ€μΌλ‘œ, νƒ€μž… μ•ˆμ „ν•˜κ³  μ§κ΄€μ μœΌλ‘œ ꡬ성할 수 μžˆλŠ” μœ ν‹Έλ¦¬ν‹° λΌμ΄λΈŒλŸ¬λ¦¬μž…λ‹ˆλ‹€.

[English](README.md)

## ✨ μ£Όμš” νŠΉμ§•

- **λ³΄μΌλŸ¬ν”Œλ ˆμ΄νŠΈ κ°μ†Œ**: λ³΅μž‘ν•œ Swagger λ°μ½”λ ˆμ΄ν„°λ₯Ό κ°„κ²°ν•˜κ²Œ μ„ μ–Έ
- **νƒ€μž… μ•ˆμ „μ„±**: Nest 컨트둀러 λ©”μ„œλ“œλ₯Ό κΈ°μ€€μœΌλ‘œ API ν‚€ 생성
- **가독성 및 일관성**: 선언적이고 λͺ…ν™•ν•œ Swagger ꡬ성
- **μœ μ§€λ³΄μˆ˜μ„± ν–₯상**: Swagger ꡬ성을 별도 파일둜 뢄리 κ°€λŠ₯
- **μœ μ—°ν•œ μ»€μŠ€ν„°λ§ˆμ΄μ§•**: 응닡 ꡬ쑰(statusKey, wrapperKey)λ₯Ό 상황에 맞게 μ‘°μ • κ°€λŠ₯

## πŸ“¦ μ„€μΉ˜

```bash
npm install nest-swagger-builder
```

### ν•„μˆ˜ Peer Dependencies:

```bash
npm install @nestjs/common @nestjs/swagger class-transformer class-validator
```

## βœ… 지원 λ²”μœ„

- **NestJS**: ^8.0.0, ^9.0.0, ^10.0.0
- **Swagger**: ^5.0.0 ~ ^8.0.0
- **class-validator**: ^0.13.2 ~ ^0.14.0
- **class-transformer**: ^0.5.1

## πŸš€ λΉ λ₯΄κ²Œ μ‹œμž‘ν•˜κΈ°

### 1. Swagger μ„ μ–Έ 파일 μž‘μ„±

```typescript
// src/controllers/swagger/user.swagger.ts
import { HttpStatus } from "@nestjs/common";
import { ApiDecoratorBuilder, ApiOperator } from "nest-swagger-builder";
import { UserController } from "../user.controller";
import { UserDto } from "../../dto/user.dto";

export const ApiUser: ApiOperator<keyof UserController> = {
  GetUsers: (apiOperationOptions) =>
    new ApiDecoratorBuilder()
      .withOperation(apiOperationOptions)
      .withBearerAuth()
      .withBodyResponse(HttpStatus.OK, "ApiUser_GetUsers", [UserDto])
      .build(),
};
```

### 2. μ»¨νŠΈλ‘€λŸ¬μ—μ„œ μ‚¬μš©

```typescript
@ApiTags("users")
@Controller("users")
export class UserController {
  @ApiUser.GetUsers({ summary: "λͺ¨λ“  μ‚¬μš©μž 쑰회" })
  @Get()
  getUsers() {
    return this.users;
  }
}
```

## 🧩 응닡 ꡬ쑰 μ»€μŠ€ν„°λ§ˆμ΄μ§• (New)

ν˜„μ—…μ—μ„œλŠ” νŒ€/μ„œλΉ„μŠ€λ§ˆλ‹€ Interceptorμ—μ„œ λ°˜ν™˜ν•˜λŠ” JSON ꡬ쑰가 λ‹€λ¦…λ‹ˆλ‹€.

예:

```typescript
// A μ„œλΉ„μŠ€
{ "statusCode": 200, "data": { ... } }

// B μ„œλΉ„μŠ€
{ "status": 200, "result": { ... } }
```

`nest-swagger-builder`λŠ” 기본적으둜 순수 Swagger ꡬ쑰(`{}`)λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
ν•˜μ§€λ§Œ λ‹€μŒ 두 κ°€μ§€ λ°©μ‹μœΌλ‘œ μ»€μŠ€ν„°λ§ˆμ΄μ§•λœ 응닡 ꡬ쑰λ₯Ό Swagger에 μ†μ‰½κ²Œ λ°˜μ˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€:

### βœ… κ°œλ³„ μ‘λ‹΅μ—μ„œ 직접 μ„€μ •

```typescript
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withBodyResponse(HttpStatus.OK, "UserDetail", UserDto, {
    statusKey: "status",
    wrapperKey: "data",
  })
  .build();
```

### βœ… 곡톡 μ„€μ • λΉŒλ” μ‚¬μš©

```typescript
// src/config/custom-swagger-builder.ts
export const CustomSwaggerBuilder = new ApiDecoratorBuilder({
  statusKey: "status",
  wrapperKey: "data",
});
```

μ‚¬μš© μ˜ˆμ‹œ:

```typescript
CustomSwaggerBuilder.withOperation(apiOperationOptions)
  .withBodyResponse(HttpStatus.OK, "UserDetail", UserDto)
  .build();
```

## πŸ“ API 응닡 νŒ¨ν„΄

### μƒνƒœ μ½”λ“œλ§Œ μžˆλŠ” 응닡

```typescript
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withBearerAuth()
  .withStatusResponse(HttpStatus.CREATED, "UserCreated", { statusKey: "statusCode" })
  .build();
```

### 데이터가 ν¬ν•¨λœ 응닡

```typescript
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withBearerAuth()
  .withBodyResponse(HttpStatus.OK, "UserProfile", UserDto, {
    statusKey: "status",
    wrapperKey: "data",
  })
  .build();
```

### λ°°μ—΄ 응닡

```typescript
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withBearerAuth()
  .withBodyResponse(HttpStatus.OK, "UsersList", [UserDto], {
    statusKey: "status",
    wrapperKey: "data",
  })
  .build();
```

### 였λ₯˜ 응닡

```typescript
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withBearerAuth()
  .withStatusResponse(HttpStatus.NO_CONTENT, "UserDeleted")
  .withUnauthorizedResponse([
    {
      name: "InvalidToken",
      error: "잘λͺ»λœ 토큰",
      description: "제곡된 인증 토큰이 μœ νš¨ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€",
    },
  ])
  .withNotFoundResponse([
    {
      name: "UserNotFound",
      error: "μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŒ",
      description: "μ£Όμ–΄μ§„ ID의 μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€",
    },
  ])
  .build();
```

### 파일 μ—…λ‘œλ“œ (Multipart Form Data)

```typescript
// 단일 파일 μ—…λ‘œλ“œ
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withFormDataRequest("ProfileImage", "image")
  .withBodyResponse(HttpStatus.CREATED, "ImageUploaded", ImageDto)
  .build();

// 닀쀑 파일 μ—…λ‘œλ“œ
new ApiDecoratorBuilder()
  .withOperation(apiOperationOptions)
  .withFormDataRequest("GalleryImages", "images", { isArray: true })
  .withBodyResponse(HttpStatus.CREATED, "ImagesUploaded", [ImageDto])
  .build();
```

μ»¨νŠΈλ‘€λŸ¬μ—μ„œ μ‚¬μš© μ˜ˆμ‹œ:

```typescript
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';

@ApiUser.UploadImageFile({ summary: "단일 이미지 μ—…λ‘œλ“œ" })
@UseInterceptors(FileInterceptor('image'))
@Post('upload')
uploadFile(@UploadedFile() file: Express.Multer.File) {
  return { filename: file.originalname, size: file.size };
}
```

## πŸ“š API μ°Έμ‘°

### ApiDecoratorBuilder

λ©”μ„œλ“œ 체이닝을 톡해 Swagger λ°μ½”λ ˆμ΄ν„°λ₯Ό μƒμ„±ν•˜λŠ” ν΄λž˜μŠ€μž…λ‹ˆλ‹€.

#### μƒμ„±μž

```typescript
new ApiDecoratorBuilder(config?: ApiDecoratorBuilderConfig)
```

| λ§€κ°œλ³€μˆ˜ | μ„€λͺ…                                 | νƒ€μž…                        |
| -------- | ------------------------------------ | --------------------------- |
| `config` | 응닡 ν˜•μ‹ κΈ°λ³Έ μ„€μ • 객체 (선택 사항) | `ApiDecoratorBuilderConfig` |

#### ApiDecoratorBuilderConfig

```typescript
interface ApiDecoratorBuilderConfig {
  wrapperKey?: string | undefined; // 응닡 데이터λ₯Ό κ°μ‹ΈλŠ” ν”„λ‘œνΌν‹° 이름 (예: "data")
  statusKey?: string | undefined; // μƒνƒœ μ½”λ“œ ν”„λ‘œνΌν‹° 이름 (예: "statusCode")
}
```

#### μ£Όμš” λ©”μ„œλ“œ

| λ©”μ„œλ“œ                     | μ„€λͺ…                         | λ§€κ°œλ³€μˆ˜                                                                       |
| -------------------------- | ---------------------------- | ------------------------------------------------------------------------------ |
| `withOperation`            | API μž‘μ—… 정보 μΆ”κ°€           | `options: ApiOperationOptions`                                                 |
| `withBearerAuth`           | Bearer 인증 μΆ”κ°€             | `name?: string`                                                                |
| `withStatusResponse`       | μƒνƒœ μ½”λ“œλ§Œ μžˆλŠ” 응닡 μΆ”κ°€   | `status: number, key: string, options?: ResponseOptions`                       |
| `withBodyResponse`         | 데이터가 ν¬ν•¨λœ 응닡 μΆ”κ°€    | `status: number, key: string, type: Type \| Type[], options?: ResponseOptions` |
| `withFormDataRequest`      | 파일 μ—…λ‘œλ“œ 지원 μΆ”κ°€        | `key: string, fileFieldName: string, options?: Record<string, any>`            |
| `withErrorResponses`       | 400 였λ₯˜ 응닡 μΆ”κ°€           | `errors: ApiErrorResponse[]`                                                   |
| `withUnauthorizedResponse` | 401 였λ₯˜ 응닡 μΆ”κ°€           | `errors: ApiErrorResponse[]`                                                   |
| `withForbiddenResponse`    | 403 였λ₯˜ 응닡 μΆ”κ°€           | `errors: ApiErrorResponse[]`                                                   |
| `withNotFoundResponse`     | 404 였λ₯˜ 응닡 μΆ”κ°€           | `errors: ApiErrorResponse[]`                                                   |
| `withDecorator`            | μ‚¬μš©μž μ •μ˜ λ°μ½”λ ˆμ΄ν„° μΆ”κ°€  | `decorator: MethodDecorator \| PropertyDecorator`                              |
| `build`                    | λͺ¨λ“  λ°μ½”λ ˆμ΄ν„° κ²°ν•© 및 λ°˜ν™˜ | -                                                                              |

### μΈν„°νŽ˜μ΄μŠ€

#### ResponseOptions

```typescript
interface ResponseOptions {
  statusKey?: string; // 응닡에 포함될 μƒνƒœ μ½”λ“œ ν•„λ“œ 이름
  wrapperKey?: string; // 응닡에 포함될 데이터 ν•„λ“œ 이름
}
```

#### ApiOperator

```typescript
type ApiOperator<M extends string> = {
  [key in Capitalize<M>]: (
    apiOperationOptions: Required<Pick<ApiOperationOptions, "summary">> & ApiOperationOptions
  ) => PropertyDecorator;
};
```

## πŸ” 예제

이 μ €μž₯μ†Œμ—λŠ” 라이브러리 μ‚¬μš© 방법을 λ³΄μ—¬μ£ΌλŠ” 예제 NestJS μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ΄ ν¬ν•¨λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€:

```bash
# μ €μž₯μ†Œ 볡제
git clone https://github.com/Kimsoo0119/nest-swagger-builder.git

# 메인 ν”„λ‘œμ νŠΈμ— μ˜μ‘΄μ„± μ„€μΉ˜
cd nest-swagger-builder
npm install
npm run build

# 예제 μ• ν”Œλ¦¬μΌ€μ΄μ…˜ μ‹€ν–‰
cd examples
npm install
npm run start:dev

# Swagger UI μ ‘κ·Ό
λΈŒλΌμš°μ €μ—μ„œ http://localhost:3000/api μ—΄κΈ°
```

## πŸ“‹ λΌμ΄μ„ΌμŠ€

이 λΌμ΄λΈŒλŸ¬λ¦¬λŠ” MIT λΌμ΄μ„ΌμŠ€ ν•˜μ— λ°°ν¬λ©λ‹ˆλ‹€ - μžμ„Έν•œ λ‚΄μš©μ€ [LICENSE](LICENSE) νŒŒμΌμ„ μ°Έμ‘°ν•˜μ„Έμš”.