-
Notifications
You must be signed in to change notification settings - Fork 11
/
generator.ts
390 lines (361 loc) · 11.3 KB
/
generator.ts
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import {
CONTROLLER_KEY,
ControllerOption,
getClassMetadata,
getMethodParamTypes,
getPropertyDataFromClass,
getPropertyMetadata,
isClass,
RouteParamTypes,
RouterOption,
RouterParamValue,
RULES_KEY,
WEB_ROUTER_KEY,
WEB_ROUTER_PARAM_KEY,
getClassExtendedMetadata,
} from '@midwayjs/decorator';
import {
SwaggerDefinition,
SwaggerDocument,
SwaggerDocumentInfo,
SwaggerDocumentParameter,
SwaggerDocumentRouter,
SwaggerDocumentTag,
} from './document';
import { ApiFormat, APIParamFormat, SWAGGER_DOCUMENT_KEY } from './createAPI';
import { SwaggerGeneratorInfoOptions } from '../interface';
export class SwaggerMetaGenerator {
document: SwaggerDocument;
constructor(options?: SwaggerGeneratorInfoOptions) {
this.document = new SwaggerDocument();
const info = new SwaggerDocumentInfo();
info.title = options?.title || 'Midway2 Swagger API';
info.version = options.version || '1.0.0';
info.description = options?.description;
info.termsOfService = options?.termsOfService;
info.contact = options?.contact;
info.license = options?.license?.name ? options?.license : undefined;
this.document.info = info;
}
generateController(module) {
const controllerOption: ControllerOption = getClassMetadata(
CONTROLLER_KEY,
module
);
const prefix = controllerOption.prefix;
const tag = new SwaggerDocumentTag();
if (prefix !== '/') {
tag.name =
controllerOption?.routerOptions.tagName ||
(/^\//.test(prefix) ? prefix.split('/')[1] : prefix);
tag.description = controllerOption?.routerOptions.description || tag.name;
} else {
tag.name = controllerOption?.routerOptions.tagName || 'default';
tag.description = controllerOption?.routerOptions.description || tag.name;
}
this.document.tags.push(tag);
// const globalMiddleware = controllerOption.routerOptions.middleware;
// get router info
const webRouterInfo: RouterOption[] = getClassMetadata(
WEB_ROUTER_KEY,
module
);
if (webRouterInfo && typeof webRouterInfo[Symbol.iterator] === 'function') {
for (const webRouter of webRouterInfo) {
let url = (prefix + webRouter.path).replace('//', '/');
url = replaceUrl(url, parseParamsInPath(url));
const router = new SwaggerDocumentRouter(webRouter.requestMethod, url);
router.tags = [tag.name];
this.generateRouter(webRouter, router, module);
this.document.addRouter(router);
}
}
}
generate() {
return this.document.toJSON();
}
generateRouter(
webRouterInfo: RouterOption,
swaggerRouter: SwaggerDocumentRouter,
module
) {
const ins = new module();
const swaggerApi: ApiFormat = getPropertyMetadata(
SWAGGER_DOCUMENT_KEY,
ins,
webRouterInfo.method
);
swaggerRouter.summary =
swaggerApi?.summary || webRouterInfo.summary || webRouterInfo.routerName;
swaggerRouter.description =
swaggerApi?.description ||
webRouterInfo.description ||
webRouterInfo.routerName;
// swaggerRouter.operationId = webRouterInfo.method;
swaggerRouter.parameters = [];
const routeArgsInfo: RouterParamValue[] =
getPropertyDataFromClass(
WEB_ROUTER_PARAM_KEY,
module,
webRouterInfo.method
) || [];
// 获取方法参数类型
const paramTypes = getMethodParamTypes(ins, webRouterInfo.method);
for (const routeArgs of routeArgsInfo) {
const swaggerParameter = new SwaggerDocumentParameter();
const argsApiInfo = swaggerApi?.params[routeArgs.index];
swaggerParameter.description = argsApiInfo?.description;
swaggerParameter.name = argsApiInfo?.name || routeArgs?.propertyData;
swaggerParameter.in = convertTypeToString(routeArgs.type);
swaggerParameter.required = argsApiInfo?.required;
swaggerParameter.deprecated = argsApiInfo?.deprecated;
swaggerParameter.allowEmptyValue = argsApiInfo?.allowEmptyValue;
swaggerParameter.example = argsApiInfo?.example;
if (swaggerParameter.in === 'path') {
swaggerParameter.required = true;
// if path not include this args, must be ignore
if (
swaggerRouter.url.indexOf('{' + swaggerParameter.name + '}') === -1
) {
continue;
}
}
if (isClass(paramTypes[routeArgs.index])) {
this.generateSwaggerDefinition(paramTypes[routeArgs.index]);
swaggerParameter.schema = {
$ref: '#/components/schemas/' + paramTypes[routeArgs.index].name,
};
} else {
swaggerParameter.schema = {
type: convertSchemaType(paramTypes[routeArgs.index].name),
name: undefined,
};
}
// add body
if (swaggerParameter.in === 'body') {
swaggerRouter.requestBody = {
description: argsApiInfo?.description || routeArgs?.propertyData,
content: {
'application/json': {
schema: swaggerParameter.schema,
},
},
};
continue;
}
// add parameter
swaggerRouter.parameters.push(swaggerParameter);
}
swaggerRouter.responses = {};
for (const apiResponse of swaggerApi?.response || []) {
// 获取方法返回值
swaggerRouter.responses[apiResponse.status] = {
description: apiResponse?.description,
headers: apiResponse?.headers,
content: apiResponse?.content,
};
}
// 兜底加个 200
if (Object.keys(swaggerRouter.responses).length === 0) {
swaggerRouter.responses = { 200: { description: '' } };
}
}
generateSwaggerDefinition(definitionClass) {
const swaggerDefinition = new SwaggerDefinition();
swaggerDefinition.name = definitionClass.name;
swaggerDefinition.type = 'object';
const properties = getClassMetadata(SWAGGER_DOCUMENT_KEY, definitionClass);
for (const propertyName in properties) {
swaggerDefinition.properties[propertyName] = {
type: properties[propertyName].type.toLowerCase(),
description: properties[propertyName].description,
example: properties[propertyName].example,
};
}
// for rule decorator
const rules = getClassExtendedMetadata(RULES_KEY, definitionClass);
if (rules) {
const properties = Object.keys(rules);
for (const property of properties) {
// set required
if (rules[property]?._flags?.presence === 'required') {
swaggerDefinition.required.push(property);
}
// 没找到这行代码对应的装饰器
// get property description
let propertyInfo: APIParamFormat = getPropertyMetadata(
SWAGGER_DOCUMENT_KEY,
definitionClass,
property
);
if (!propertyInfo) {
propertyInfo = this.generateSwaggerByJoiProperty(
rules[property],
joinCamel(definitionClass.name, property)
);
}
if (swaggerDefinition.properties[property] && !propertyInfo?.$ref) {
mixWhenPropertyEmpty(
swaggerDefinition.properties[property],
propertyInfo
);
} else {
swaggerDefinition.properties[property] = propertyInfo;
}
}
}
this.document.definitions.push(swaggerDefinition);
// DTO
for (const key in properties) {
// 必须加了属性装饰器
if (
!rules?.[key] &&
properties[key].originDesign &&
!properties[key].isBaseType
) {
this.generateSwaggerDefinition(properties[key].originDesign);
// 把复杂类型属性指向新的定义
swaggerDefinition.properties[key] = {};
swaggerDefinition.properties[key]['$ref'] =
'#/components/schemas/' + properties[key].type;
}
}
}
generateSwaggerByJoiProperty(joiSchema, pathName?: string) {
const describe = joiSchema.describe();
if (describe.flags?.presence === 'forbidden') {
return undefined;
}
let define: any = {
type: describe.type,
default: describe.flags?.default,
description: describe.flags?.description,
example: describe.examples?.join(' '),
};
let min;
let max;
for (const r of describe.rules || []) {
if (r.name === 'min' && r.args) {
min = r.args.limit;
} else if (r.name === 'max') {
max = r.args.limit;
}
}
if (describe.flags?.only) {
define.enum = describe.allow;
}
if (describe.invalid) {
define.not = { enum: describe.invalid };
}
switch (describe.type) {
case 'string':
define.minLength = min;
define.maxLength = max;
break;
case 'number':
define.minimum = min;
define.maximum = max;
if (describe.rules?.some(r => r.name === 'integer')) {
define.type = 'integer';
}
break;
case 'date':
define.type = 'string';
define.format = 'date-time';
break;
case 'object': {
const swaggerDefinition = new SwaggerDefinition();
const schemaMeta = describe.metas?.find(m => Boolean(m.id));
swaggerDefinition.name = schemaMeta?.id || pathName;
swaggerDefinition.type = 'object';
swaggerDefinition.required = [];
for (const prop of joiSchema.$_terms?.keys) {
if (prop.schema._flags?.presence === 'required') {
swaggerDefinition.required.push(prop.key);
}
swaggerDefinition.properties[prop.key] =
this.generateSwaggerByJoiProperty(
prop.schema,
joinCamel(pathName, prop.key)
);
}
this.document.definitions.push(swaggerDefinition);
define = { $ref: '#/components/schemas/' + swaggerDefinition.name };
break;
}
case 'array':
define.minItems = min;
define.maxItems = max;
if (joiSchema.$_terms.items[0]) {
define.items = this.generateSwaggerByJoiProperty(
joiSchema.$_terms.items[0],
pathName
);
}
}
return define;
}
}
function joinCamel(word1, word2) {
return `${word1}${word2[0].toUpperCase()}${word2.slice(1)}`;
}
function convertTypeToString(type: RouteParamTypes) {
switch (type) {
case RouteParamTypes.HEADERS:
return 'header';
case RouteParamTypes.QUERY:
return 'query';
case RouteParamTypes.PARAM:
return 'path';
case RouteParamTypes.BODY:
return 'body';
default:
return 'header';
}
}
/**
* 解释路由上的参数
* @param url
*/
function parseParamsInPath(url: string) {
const names: string[] = [];
url.split('/').forEach(item => {
if (item.startsWith(':')) {
const paramName = item.substr(1);
names.push(paramName);
}
});
return names;
}
/**
* 替换成 openapi 的url
* @param url
* @param names
*/
function replaceUrl(url: string, names: string[]) {
names.forEach(n => {
url = url.replace(`:${n}`, `{${n}}`);
});
return url;
}
function convertSchemaType(value) {
switch (value) {
case 'Object':
return 'object';
case 'Boolean':
return 'boolean';
case 'Number':
return 'number';
case 'String':
return 'string';
default:
return 'object';
}
}
function mixWhenPropertyEmpty(target, source) {
for (const key in source) {
if (!target[key] && source[key]) {
target[key] = source[key];
}
}
}