@dazhicheng/openapi 1.1.10 → 1.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/util.d.ts +1 -1
- package/package.json +1 -1
- package/src/serviceGenerator.ts +1093 -1092
- package/src/util.ts +4 -3
- package/templates/interface.njk +54 -54
- package/templates/serviceIndex.njk +14 -14
package/src/serviceGenerator.ts
CHANGED
|
@@ -1,1092 +1,1093 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from "fs";
|
|
2
|
-
import glob from "glob";
|
|
3
|
-
import { camelCase, isBoolean, isArray } from "lodash-es";
|
|
4
|
-
import nunjucks from "nunjucks";
|
|
5
|
-
import type {
|
|
6
|
-
ContentObject,
|
|
7
|
-
OpenAPIObject,
|
|
8
|
-
OperationObject,
|
|
9
|
-
ParameterObject,
|
|
10
|
-
PathItemObject,
|
|
11
|
-
ReferenceObject,
|
|
12
|
-
RequestBodyObject,
|
|
13
|
-
ResponseObject,
|
|
14
|
-
ResponsesObject,
|
|
15
|
-
SchemaObject,
|
|
16
|
-
} from "openapi3-ts";
|
|
17
|
-
import { join, dirname } from "path";
|
|
18
|
-
import { fileURLToPath } from "url";
|
|
19
|
-
|
|
20
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
21
|
-
const __dirname = dirname(__filename);
|
|
22
|
-
import ReservedDict from "reserved-words";
|
|
23
|
-
import rimraf from "rimraf";
|
|
24
|
-
import pinyin from "tiny-pinyin";
|
|
25
|
-
import numberToWords from "number-to-words";
|
|
26
|
-
import type { GenerateServiceProps } from "./index";
|
|
27
|
-
import Log from "./log";
|
|
28
|
-
import { stripDot, writeFile } from "./util";
|
|
29
|
-
const BASE_DIRS = ["service", "services"];
|
|
30
|
-
|
|
31
|
-
export type TypescriptFileType = "interface" | "serviceController" | "serviceIndex";
|
|
32
|
-
|
|
33
|
-
export interface APIDataType extends OperationObject {
|
|
34
|
-
path: string;
|
|
35
|
-
method: string;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export type TagAPIDataType = Record<string, APIDataType[]>;
|
|
39
|
-
|
|
40
|
-
export interface MappingItemType {
|
|
41
|
-
antTechApi: string;
|
|
42
|
-
popAction: string;
|
|
43
|
-
popProduct: string;
|
|
44
|
-
antTechVersion: string;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export interface ControllerType {
|
|
48
|
-
fileName: string;
|
|
49
|
-
controllerName: string;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export const getPath = () => {
|
|
53
|
-
const cwd = process.cwd();
|
|
54
|
-
return existsSync(join(cwd, "src")) ? join(cwd, "src") : cwd;
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
// 类型声明过滤关键字
|
|
58
|
-
const resolveTypeName = (typeName: string) => {
|
|
59
|
-
if (ReservedDict.check(typeName)) {
|
|
60
|
-
return `__openAPI__${typeName}`;
|
|
61
|
-
}
|
|
62
|
-
const typeLastName = typeName!.split("/")!.pop()!.split(".").pop();
|
|
63
|
-
|
|
64
|
-
let name = typeLastName!
|
|
65
|
-
.replace(/[-_ ](\w)/g, (_all, letter) => letter.toUpperCase())
|
|
66
|
-
.replace(/[^\w^\s^\u4e00-\u9fa5]/gi, "");
|
|
67
|
-
|
|
68
|
-
// 当model名称是number开头的时候,ts会报错。这种场景一般发生在后端定义的名称是中文
|
|
69
|
-
if (name === "_" || /^\d+$/.test(name)) {
|
|
70
|
-
Log("⚠️ models不能以number开头,原因可能是Model定义名称为中文, 建议联系后台修改");
|
|
71
|
-
return `Pinyin_${name}`;
|
|
72
|
-
}
|
|
73
|
-
// 前面的解析可能会吧类似"2.0"之类的tag文字解析成首字母带数字的key
|
|
74
|
-
// 后面要是再带点别的字符在生成ts className的时候会由于首字符带数字导致非法变量报错
|
|
75
|
-
// 这里做一个统一处理
|
|
76
|
-
if (/^\d/.test(name)) {
|
|
77
|
-
const firstChar = parseInt(name[0]);
|
|
78
|
-
name = `${numberToWords.toWords(firstChar)}${name.substring(1)}`;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
if (!/[\u3220-\uFA29]/.test(name) && !/^\d$/.test(name)) {
|
|
82
|
-
return name;
|
|
83
|
-
}
|
|
84
|
-
const noBlankName = name.replace(/ +/g, "");
|
|
85
|
-
return pinyin.convertToPinyin(noBlankName, "", true);
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
function getRefName(refObject: any): string {
|
|
89
|
-
if (typeof refObject !== "object" || !refObject.$ref) {
|
|
90
|
-
return refObject;
|
|
91
|
-
}
|
|
92
|
-
const refPaths = refObject.$ref.split("/");
|
|
93
|
-
return resolveTypeName(refPaths[refPaths.length - 1]) as string;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
const defaultGetType = (schemaObject: SchemaObject | undefined, namespace: string = ""): string => {
|
|
97
|
-
if (schemaObject === undefined || schemaObject === null) {
|
|
98
|
-
return "any";
|
|
99
|
-
}
|
|
100
|
-
if (typeof schemaObject !== "object") {
|
|
101
|
-
return schemaObject;
|
|
102
|
-
}
|
|
103
|
-
if (schemaObject.$ref) {
|
|
104
|
-
return [namespace, getRefName(schemaObject)].filter(s => s).join(".");
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
let { type } = schemaObject as any;
|
|
108
|
-
|
|
109
|
-
const numberEnum = ["integer", "long", "float", "double", "number", "int", "float", "double", "int32", "int64"];
|
|
110
|
-
|
|
111
|
-
const dateEnum = ["Date", "date", "dateTime", "date-time", "datetime"];
|
|
112
|
-
|
|
113
|
-
const stringEnum = ["string", "email", "password", "url", "byte", "binary"];
|
|
114
|
-
|
|
115
|
-
if (type === "null") {
|
|
116
|
-
return "null";
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
if (numberEnum.includes(schemaObject.format)) {
|
|
120
|
-
type = "number";
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
if (schemaObject.enum) {
|
|
124
|
-
type = "enum";
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
if (numberEnum.includes(type)) {
|
|
128
|
-
return "number";
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
if (dateEnum.includes(type)) {
|
|
132
|
-
return "Date";
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
if (stringEnum.includes(type)) {
|
|
136
|
-
return "string";
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
if (type === "boolean") {
|
|
140
|
-
return "boolean";
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
if (type === "array") {
|
|
144
|
-
let { items } = schemaObject;
|
|
145
|
-
if (schemaObject.schema) {
|
|
146
|
-
items = schemaObject.schema.items;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
if (Array.isArray(items)) {
|
|
150
|
-
const arrayItemType = (items as any)
|
|
151
|
-
.map(subType => defaultGetType(subType.schema || subType, namespace))
|
|
152
|
-
.toString();
|
|
153
|
-
return `[${arrayItemType}]`;
|
|
154
|
-
}
|
|
155
|
-
const arrayType = defaultGetType(items, namespace);
|
|
156
|
-
return arrayType.includes(" | ") ? `(${arrayType})[]` : `${arrayType}[]`;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
if (type === "enum") {
|
|
160
|
-
return Array.isArray(schemaObject.enum)
|
|
161
|
-
? Array.from(
|
|
162
|
-
new Set(
|
|
163
|
-
schemaObject.enum.map(v => (typeof v === "string" ? `"${v.replace(/"/g, '"')}"` : defaultGetType(v))),
|
|
164
|
-
),
|
|
165
|
-
).join(" | ")
|
|
166
|
-
: "string";
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
if (schemaObject.oneOf && schemaObject.oneOf.length) {
|
|
170
|
-
return schemaObject.oneOf.map(item => defaultGetType(item, namespace)).join(" | ");
|
|
171
|
-
}
|
|
172
|
-
if (schemaObject.anyOf && schemaObject.anyOf.length) {
|
|
173
|
-
return schemaObject.anyOf.map(item => defaultGetType(item, namespace)).join(" | ");
|
|
174
|
-
}
|
|
175
|
-
if (schemaObject.allOf && schemaObject.allOf.length) {
|
|
176
|
-
return `(${schemaObject.allOf.map(item => defaultGetType(item, namespace)).join(" & ")})`;
|
|
177
|
-
}
|
|
178
|
-
if (schemaObject.type === "object" || schemaObject.properties) {
|
|
179
|
-
if (!Object.keys(schemaObject.properties || {}).length) {
|
|
180
|
-
return "Record<string, any>";
|
|
181
|
-
}
|
|
182
|
-
return `{ ${Object.keys(schemaObject.properties)
|
|
183
|
-
.map(key => {
|
|
184
|
-
let required = false;
|
|
185
|
-
if (isBoolean(schemaObject.required) && schemaObject.required) {
|
|
186
|
-
required = true;
|
|
187
|
-
}
|
|
188
|
-
if (isArray(schemaObject.required) && schemaObject.required.includes(key)) {
|
|
189
|
-
required = true;
|
|
190
|
-
}
|
|
191
|
-
if (
|
|
192
|
-
"required" in (schemaObject.properties[key] || {}) &&
|
|
193
|
-
((schemaObject.properties[key] || {}) as any).required
|
|
194
|
-
) {
|
|
195
|
-
required = true;
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* 将类型属性变为字符串,兼容错误格式如:
|
|
199
|
-
* 3d_tile(数字开头)等错误命名,
|
|
200
|
-
* 在后面进行格式化的时候会将正确的字符串转换为正常形式,
|
|
201
|
-
* 错误的继续保留字符串。
|
|
202
|
-
* */
|
|
203
|
-
return `'${key}'${required ? "" : "?"}: ${defaultGetType(
|
|
204
|
-
schemaObject.properties && schemaObject.properties[key],
|
|
205
|
-
namespace,
|
|
206
|
-
)}; `;
|
|
207
|
-
})
|
|
208
|
-
.join("")}}`;
|
|
209
|
-
}
|
|
210
|
-
return "any";
|
|
211
|
-
};
|
|
212
|
-
|
|
213
|
-
export const getGenInfo = (isDirExist: boolean, appName: string, absSrcPath: string) => {
|
|
214
|
-
// dir 不存在,则没有占用,且为第一次
|
|
215
|
-
if (!isDirExist) {
|
|
216
|
-
return [false, true];
|
|
217
|
-
}
|
|
218
|
-
const indexList = glob.sync(`@(${BASE_DIRS.join("|")})/${appName}/index.@(js|ts)`, {
|
|
219
|
-
cwd: absSrcPath,
|
|
220
|
-
});
|
|
221
|
-
// dir 存在,且 index 存在
|
|
222
|
-
if (indexList && indexList.length) {
|
|
223
|
-
const indexFile = join(absSrcPath, indexList[0]);
|
|
224
|
-
try {
|
|
225
|
-
const line = (readFileSync(indexFile, "utf-8") || "").split(/\r?\n/).slice(0, 3).join("");
|
|
226
|
-
// dir 存在,index 存在, 且 index 是我们生成的。则未占用,且不是第一次
|
|
227
|
-
if (line.includes("// API 更新时间:")) {
|
|
228
|
-
return [false, false];
|
|
229
|
-
}
|
|
230
|
-
// dir 存在,index 存在,且 index 内容不是我们生成的。此时如果 openAPI 子文件存在,就不是第一次,否则是第一次
|
|
231
|
-
return [true, !existsSync(join(indexFile, "openAPI"))];
|
|
232
|
-
} catch (error: any) {
|
|
233
|
-
console.error("getGenInfo error:", error);
|
|
234
|
-
// 因为 glob 已经拿到了这个文件,但没权限读,所以当作 dirUsed, 在子目录重新新建,所以当作 firstTime
|
|
235
|
-
return [true, true];
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
// dir 存在,index 不存在, 冲突,第一次要看 dir 下有没有 openAPI 文件夹
|
|
239
|
-
return [
|
|
240
|
-
true,
|
|
241
|
-
!(
|
|
242
|
-
existsSync(join(absSrcPath, BASE_DIRS[0]!, appName, "openAPI")) ||
|
|
243
|
-
existsSync(join(absSrcPath, BASE_DIRS[1]!, appName, "openAPI"))
|
|
244
|
-
),
|
|
245
|
-
];
|
|
246
|
-
};
|
|
247
|
-
|
|
248
|
-
const DEFAULT_SCHEMA: SchemaObject = {
|
|
249
|
-
type: "object",
|
|
250
|
-
properties: { id: { type: "number" } },
|
|
251
|
-
};
|
|
252
|
-
|
|
253
|
-
const DEFAULT_PATH_PARAM: ParameterObject = {
|
|
254
|
-
in: "path",
|
|
255
|
-
name: null,
|
|
256
|
-
schema: {
|
|
257
|
-
type: "string",
|
|
258
|
-
},
|
|
259
|
-
required: true,
|
|
260
|
-
isObject: false,
|
|
261
|
-
type: "string",
|
|
262
|
-
};
|
|
263
|
-
|
|
264
|
-
function defaultGetFileTag(operationObject: OperationObject, apiPath: string, _apiMethod: string) {
|
|
265
|
-
return operationObject["x-swagger-router-controller"]
|
|
266
|
-
? [operationObject["x-swagger-router-controller"]]
|
|
267
|
-
: operationObject.tags || [operationObject.operationId] || [apiPath.replace("/", "").split("/")[1]];
|
|
268
|
-
}
|
|
269
|
-
class ServiceGenerator {
|
|
270
|
-
protected apiData: TagAPIDataType = {};
|
|
271
|
-
|
|
272
|
-
protected classNameList: ControllerType[] = [];
|
|
273
|
-
|
|
274
|
-
protected version: string;
|
|
275
|
-
|
|
276
|
-
protected mappings: MappingItemType[] = [];
|
|
277
|
-
|
|
278
|
-
protected finalPath: string;
|
|
279
|
-
|
|
280
|
-
protected config: GenerateServiceProps;
|
|
281
|
-
protected openAPIData: OpenAPIObject;
|
|
282
|
-
|
|
283
|
-
constructor(config: GenerateServiceProps, openAPIData: OpenAPIObject) {
|
|
284
|
-
this.finalPath = "";
|
|
285
|
-
this.config = {
|
|
286
|
-
projectName: "api",
|
|
287
|
-
templatesFolder: join(__dirname, "../", "templates"),
|
|
288
|
-
...config,
|
|
289
|
-
};
|
|
290
|
-
if (this.config.hook?.afterOpenApiDataInited) {
|
|
291
|
-
this.openAPIData = this.config.hook.afterOpenApiDataInited(openAPIData) || openAPIData;
|
|
292
|
-
} else {
|
|
293
|
-
this.openAPIData = openAPIData;
|
|
294
|
-
}
|
|
295
|
-
const { info } = this.openAPIData;
|
|
296
|
-
const basePath = "";
|
|
297
|
-
this.version = info.version;
|
|
298
|
-
const hookCustomFileNames = this.config.hook?.customFileNames || defaultGetFileTag;
|
|
299
|
-
const specifiedPaths = this.config.specifiedPaths;
|
|
300
|
-
|
|
301
|
-
Object.keys(this.openAPIData.paths || {}).forEach(p => {
|
|
302
|
-
if (specifiedPaths?.length && !specifiedPaths.includes(p)) {
|
|
303
|
-
return;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
const pathItem: PathItemObject = this.openAPIData.paths[p];
|
|
307
|
-
|
|
308
|
-
["get", "put", "post", "delete", "patch"].forEach(method => {
|
|
309
|
-
const operationObject: OperationObject = pathItem[method];
|
|
310
|
-
if (!operationObject) {
|
|
311
|
-
return;
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
let tags = hookCustomFileNames(operationObject, p, method);
|
|
315
|
-
if (!tags) {
|
|
316
|
-
tags = defaultGetFileTag(operationObject, p, method);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
tags.forEach(tagString => {
|
|
320
|
-
const tag = this.config.isCamelCase ? camelCase(resolveTypeName(tagString)) : resolveTypeName(tagString);
|
|
321
|
-
|
|
322
|
-
if (!this.apiData[tag]) {
|
|
323
|
-
this.apiData[tag] = [];
|
|
324
|
-
}
|
|
325
|
-
this.apiData[tag].push({
|
|
326
|
-
path: `${basePath}${p}`,
|
|
327
|
-
method,
|
|
328
|
-
...operationObject,
|
|
329
|
-
});
|
|
330
|
-
});
|
|
331
|
-
});
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
public async genFile() {
|
|
336
|
-
const basePath = this.config.serversPath || "./src/service";
|
|
337
|
-
try {
|
|
338
|
-
const finalPath = join(basePath, this.config.projectName!);
|
|
339
|
-
this.finalPath = finalPath;
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
rimraf.sync(
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
const
|
|
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
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
const
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
//
|
|
429
|
-
//
|
|
430
|
-
|
|
431
|
-
const
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
const {
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
newApi.
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
.
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
schema.properties
|
|
586
|
-
|
|
587
|
-
!(
|
|
588
|
-
|
|
589
|
-
["
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
const
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
resolved.props
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
p.format === "
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
const
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
const
|
|
661
|
-
const
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
const
|
|
670
|
-
const
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
.
|
|
703
|
-
.
|
|
704
|
-
|
|
705
|
-
const
|
|
706
|
-
const
|
|
707
|
-
const
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
if (obj
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
const
|
|
765
|
-
const
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
components
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
const
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
data
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
.
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
*
|
|
1011
|
-
*
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
.
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
.
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
}
|
|
1091
|
-
|
|
1092
|
-
|
|
1
|
+
import { existsSync, readFileSync, readdirSync } from "fs";
|
|
2
|
+
import glob from "glob";
|
|
3
|
+
import { camelCase, isBoolean, isArray } from "lodash-es";
|
|
4
|
+
import nunjucks from "nunjucks";
|
|
5
|
+
import type {
|
|
6
|
+
ContentObject,
|
|
7
|
+
OpenAPIObject,
|
|
8
|
+
OperationObject,
|
|
9
|
+
ParameterObject,
|
|
10
|
+
PathItemObject,
|
|
11
|
+
ReferenceObject,
|
|
12
|
+
RequestBodyObject,
|
|
13
|
+
ResponseObject,
|
|
14
|
+
ResponsesObject,
|
|
15
|
+
SchemaObject,
|
|
16
|
+
} from "openapi3-ts";
|
|
17
|
+
import { join, dirname } from "path";
|
|
18
|
+
import { fileURLToPath } from "url";
|
|
19
|
+
|
|
20
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
21
|
+
const __dirname = dirname(__filename);
|
|
22
|
+
import ReservedDict from "reserved-words";
|
|
23
|
+
import rimraf from "rimraf";
|
|
24
|
+
import pinyin from "tiny-pinyin";
|
|
25
|
+
import numberToWords from "number-to-words";
|
|
26
|
+
import type { GenerateServiceProps } from "./index";
|
|
27
|
+
import Log from "./log";
|
|
28
|
+
import { stripDot, writeFile } from "./util";
|
|
29
|
+
const BASE_DIRS = ["service", "services"];
|
|
30
|
+
|
|
31
|
+
export type TypescriptFileType = "interface" | "serviceController" | "serviceIndex";
|
|
32
|
+
|
|
33
|
+
export interface APIDataType extends OperationObject {
|
|
34
|
+
path: string;
|
|
35
|
+
method: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type TagAPIDataType = Record<string, APIDataType[]>;
|
|
39
|
+
|
|
40
|
+
export interface MappingItemType {
|
|
41
|
+
antTechApi: string;
|
|
42
|
+
popAction: string;
|
|
43
|
+
popProduct: string;
|
|
44
|
+
antTechVersion: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ControllerType {
|
|
48
|
+
fileName: string;
|
|
49
|
+
controllerName: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const getPath = () => {
|
|
53
|
+
const cwd = process.cwd();
|
|
54
|
+
return existsSync(join(cwd, "src")) ? join(cwd, "src") : cwd;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// 类型声明过滤关键字
|
|
58
|
+
const resolveTypeName = (typeName: string) => {
|
|
59
|
+
if (ReservedDict.check(typeName)) {
|
|
60
|
+
return `__openAPI__${typeName}`;
|
|
61
|
+
}
|
|
62
|
+
const typeLastName = typeName!.split("/")!.pop()!.split(".").pop();
|
|
63
|
+
|
|
64
|
+
let name = typeLastName!
|
|
65
|
+
.replace(/[-_ ](\w)/g, (_all, letter) => letter.toUpperCase())
|
|
66
|
+
.replace(/[^\w^\s^\u4e00-\u9fa5]/gi, "");
|
|
67
|
+
|
|
68
|
+
// 当model名称是number开头的时候,ts会报错。这种场景一般发生在后端定义的名称是中文
|
|
69
|
+
if (name === "_" || /^\d+$/.test(name)) {
|
|
70
|
+
Log("⚠️ models不能以number开头,原因可能是Model定义名称为中文, 建议联系后台修改");
|
|
71
|
+
return `Pinyin_${name}`;
|
|
72
|
+
}
|
|
73
|
+
// 前面的解析可能会吧类似"2.0"之类的tag文字解析成首字母带数字的key
|
|
74
|
+
// 后面要是再带点别的字符在生成ts className的时候会由于首字符带数字导致非法变量报错
|
|
75
|
+
// 这里做一个统一处理
|
|
76
|
+
if (/^\d/.test(name)) {
|
|
77
|
+
const firstChar = parseInt(name[0]);
|
|
78
|
+
name = `${numberToWords.toWords(firstChar)}${name.substring(1)}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (!/[\u3220-\uFA29]/.test(name) && !/^\d$/.test(name)) {
|
|
82
|
+
return name;
|
|
83
|
+
}
|
|
84
|
+
const noBlankName = name.replace(/ +/g, "");
|
|
85
|
+
return pinyin.convertToPinyin(noBlankName, "", true);
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
function getRefName(refObject: any): string {
|
|
89
|
+
if (typeof refObject !== "object" || !refObject.$ref) {
|
|
90
|
+
return refObject;
|
|
91
|
+
}
|
|
92
|
+
const refPaths = refObject.$ref.split("/");
|
|
93
|
+
return resolveTypeName(refPaths[refPaths.length - 1]) as string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const defaultGetType = (schemaObject: SchemaObject | undefined, namespace: string = ""): string => {
|
|
97
|
+
if (schemaObject === undefined || schemaObject === null) {
|
|
98
|
+
return "any";
|
|
99
|
+
}
|
|
100
|
+
if (typeof schemaObject !== "object") {
|
|
101
|
+
return schemaObject;
|
|
102
|
+
}
|
|
103
|
+
if (schemaObject.$ref) {
|
|
104
|
+
return [namespace, getRefName(schemaObject)].filter(s => s).join(".");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
let { type } = schemaObject as any;
|
|
108
|
+
|
|
109
|
+
const numberEnum = ["integer", "long", "float", "double", "number", "int", "float", "double", "int32", "int64"];
|
|
110
|
+
|
|
111
|
+
const dateEnum = ["Date", "date", "dateTime", "date-time", "datetime"];
|
|
112
|
+
|
|
113
|
+
const stringEnum = ["string", "email", "password", "url", "byte", "binary"];
|
|
114
|
+
|
|
115
|
+
if (type === "null") {
|
|
116
|
+
return "null";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (numberEnum.includes(schemaObject.format)) {
|
|
120
|
+
type = "number";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (schemaObject.enum) {
|
|
124
|
+
type = "enum";
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (numberEnum.includes(type)) {
|
|
128
|
+
return "number";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (dateEnum.includes(type)) {
|
|
132
|
+
return "Date";
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (stringEnum.includes(type)) {
|
|
136
|
+
return "string";
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (type === "boolean") {
|
|
140
|
+
return "boolean";
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (type === "array") {
|
|
144
|
+
let { items } = schemaObject;
|
|
145
|
+
if (schemaObject.schema) {
|
|
146
|
+
items = schemaObject.schema.items;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (Array.isArray(items)) {
|
|
150
|
+
const arrayItemType = (items as any)
|
|
151
|
+
.map(subType => defaultGetType(subType.schema || subType, namespace))
|
|
152
|
+
.toString();
|
|
153
|
+
return `[${arrayItemType}]`;
|
|
154
|
+
}
|
|
155
|
+
const arrayType = defaultGetType(items, namespace);
|
|
156
|
+
return arrayType.includes(" | ") ? `(${arrayType})[]` : `${arrayType}[]`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (type === "enum") {
|
|
160
|
+
return Array.isArray(schemaObject.enum)
|
|
161
|
+
? Array.from(
|
|
162
|
+
new Set(
|
|
163
|
+
schemaObject.enum.map(v => (typeof v === "string" ? `"${v.replace(/"/g, '"')}"` : defaultGetType(v))),
|
|
164
|
+
),
|
|
165
|
+
).join(" | ")
|
|
166
|
+
: "string";
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (schemaObject.oneOf && schemaObject.oneOf.length) {
|
|
170
|
+
return schemaObject.oneOf.map(item => defaultGetType(item, namespace)).join(" | ");
|
|
171
|
+
}
|
|
172
|
+
if (schemaObject.anyOf && schemaObject.anyOf.length) {
|
|
173
|
+
return schemaObject.anyOf.map(item => defaultGetType(item, namespace)).join(" | ");
|
|
174
|
+
}
|
|
175
|
+
if (schemaObject.allOf && schemaObject.allOf.length) {
|
|
176
|
+
return `(${schemaObject.allOf.map(item => defaultGetType(item, namespace)).join(" & ")})`;
|
|
177
|
+
}
|
|
178
|
+
if (schemaObject.type === "object" || schemaObject.properties) {
|
|
179
|
+
if (!Object.keys(schemaObject.properties || {}).length) {
|
|
180
|
+
return "Record<string, any>";
|
|
181
|
+
}
|
|
182
|
+
return `{ ${Object.keys(schemaObject.properties)
|
|
183
|
+
.map(key => {
|
|
184
|
+
let required = false;
|
|
185
|
+
if (isBoolean(schemaObject.required) && schemaObject.required) {
|
|
186
|
+
required = true;
|
|
187
|
+
}
|
|
188
|
+
if (isArray(schemaObject.required) && schemaObject.required.includes(key)) {
|
|
189
|
+
required = true;
|
|
190
|
+
}
|
|
191
|
+
if (
|
|
192
|
+
"required" in (schemaObject.properties[key] || {}) &&
|
|
193
|
+
((schemaObject.properties[key] || {}) as any).required
|
|
194
|
+
) {
|
|
195
|
+
required = true;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* 将类型属性变为字符串,兼容错误格式如:
|
|
199
|
+
* 3d_tile(数字开头)等错误命名,
|
|
200
|
+
* 在后面进行格式化的时候会将正确的字符串转换为正常形式,
|
|
201
|
+
* 错误的继续保留字符串。
|
|
202
|
+
* */
|
|
203
|
+
return `'${key}'${required ? "" : "?"}: ${defaultGetType(
|
|
204
|
+
schemaObject.properties && schemaObject.properties[key],
|
|
205
|
+
namespace,
|
|
206
|
+
)}; `;
|
|
207
|
+
})
|
|
208
|
+
.join("")}}`;
|
|
209
|
+
}
|
|
210
|
+
return "any";
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
export const getGenInfo = (isDirExist: boolean, appName: string, absSrcPath: string) => {
|
|
214
|
+
// dir 不存在,则没有占用,且为第一次
|
|
215
|
+
if (!isDirExist) {
|
|
216
|
+
return [false, true];
|
|
217
|
+
}
|
|
218
|
+
const indexList = glob.sync(`@(${BASE_DIRS.join("|")})/${appName}/index.@(js|ts)`, {
|
|
219
|
+
cwd: absSrcPath,
|
|
220
|
+
});
|
|
221
|
+
// dir 存在,且 index 存在
|
|
222
|
+
if (indexList && indexList.length) {
|
|
223
|
+
const indexFile = join(absSrcPath, indexList[0]);
|
|
224
|
+
try {
|
|
225
|
+
const line = (readFileSync(indexFile, "utf-8") || "").split(/\r?\n/).slice(0, 3).join("");
|
|
226
|
+
// dir 存在,index 存在, 且 index 是我们生成的。则未占用,且不是第一次
|
|
227
|
+
if (line.includes("// API 更新时间:")) {
|
|
228
|
+
return [false, false];
|
|
229
|
+
}
|
|
230
|
+
// dir 存在,index 存在,且 index 内容不是我们生成的。此时如果 openAPI 子文件存在,就不是第一次,否则是第一次
|
|
231
|
+
return [true, !existsSync(join(indexFile, "openAPI"))];
|
|
232
|
+
} catch (error: any) {
|
|
233
|
+
console.error("getGenInfo error:", error);
|
|
234
|
+
// 因为 glob 已经拿到了这个文件,但没权限读,所以当作 dirUsed, 在子目录重新新建,所以当作 firstTime
|
|
235
|
+
return [true, true];
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// dir 存在,index 不存在, 冲突,第一次要看 dir 下有没有 openAPI 文件夹
|
|
239
|
+
return [
|
|
240
|
+
true,
|
|
241
|
+
!(
|
|
242
|
+
existsSync(join(absSrcPath, BASE_DIRS[0]!, appName, "openAPI")) ||
|
|
243
|
+
existsSync(join(absSrcPath, BASE_DIRS[1]!, appName, "openAPI"))
|
|
244
|
+
),
|
|
245
|
+
];
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const DEFAULT_SCHEMA: SchemaObject = {
|
|
249
|
+
type: "object",
|
|
250
|
+
properties: { id: { type: "number" } },
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
const DEFAULT_PATH_PARAM: ParameterObject = {
|
|
254
|
+
in: "path",
|
|
255
|
+
name: null,
|
|
256
|
+
schema: {
|
|
257
|
+
type: "string",
|
|
258
|
+
},
|
|
259
|
+
required: true,
|
|
260
|
+
isObject: false,
|
|
261
|
+
type: "string",
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
function defaultGetFileTag(operationObject: OperationObject, apiPath: string, _apiMethod: string) {
|
|
265
|
+
return operationObject["x-swagger-router-controller"]
|
|
266
|
+
? [operationObject["x-swagger-router-controller"]]
|
|
267
|
+
: operationObject.tags || [operationObject.operationId] || [apiPath.replace("/", "").split("/")[1]];
|
|
268
|
+
}
|
|
269
|
+
class ServiceGenerator {
|
|
270
|
+
protected apiData: TagAPIDataType = {};
|
|
271
|
+
|
|
272
|
+
protected classNameList: ControllerType[] = [];
|
|
273
|
+
|
|
274
|
+
protected version: string;
|
|
275
|
+
|
|
276
|
+
protected mappings: MappingItemType[] = [];
|
|
277
|
+
|
|
278
|
+
protected finalPath: string;
|
|
279
|
+
|
|
280
|
+
protected config: GenerateServiceProps;
|
|
281
|
+
protected openAPIData: OpenAPIObject;
|
|
282
|
+
|
|
283
|
+
constructor(config: GenerateServiceProps, openAPIData: OpenAPIObject) {
|
|
284
|
+
this.finalPath = "";
|
|
285
|
+
this.config = {
|
|
286
|
+
projectName: "api",
|
|
287
|
+
templatesFolder: join(__dirname, "../", "templates"),
|
|
288
|
+
...config,
|
|
289
|
+
};
|
|
290
|
+
if (this.config.hook?.afterOpenApiDataInited) {
|
|
291
|
+
this.openAPIData = this.config.hook.afterOpenApiDataInited(openAPIData) || openAPIData;
|
|
292
|
+
} else {
|
|
293
|
+
this.openAPIData = openAPIData;
|
|
294
|
+
}
|
|
295
|
+
const { info } = this.openAPIData;
|
|
296
|
+
const basePath = "";
|
|
297
|
+
this.version = info.version;
|
|
298
|
+
const hookCustomFileNames = this.config.hook?.customFileNames || defaultGetFileTag;
|
|
299
|
+
const specifiedPaths = this.config.specifiedPaths;
|
|
300
|
+
|
|
301
|
+
Object.keys(this.openAPIData.paths || {}).forEach(p => {
|
|
302
|
+
if (specifiedPaths?.length && !specifiedPaths.includes(p)) {
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const pathItem: PathItemObject = this.openAPIData.paths[p];
|
|
307
|
+
|
|
308
|
+
["get", "put", "post", "delete", "patch"].forEach(method => {
|
|
309
|
+
const operationObject: OperationObject = pathItem[method];
|
|
310
|
+
if (!operationObject) {
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
let tags = hookCustomFileNames(operationObject, p, method);
|
|
315
|
+
if (!tags) {
|
|
316
|
+
tags = defaultGetFileTag(operationObject, p, method);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
tags.forEach(tagString => {
|
|
320
|
+
const tag = this.config.isCamelCase ? camelCase(resolveTypeName(tagString)) : resolveTypeName(tagString);
|
|
321
|
+
|
|
322
|
+
if (!this.apiData[tag]) {
|
|
323
|
+
this.apiData[tag] = [];
|
|
324
|
+
}
|
|
325
|
+
this.apiData[tag].push({
|
|
326
|
+
path: `${basePath}${p}`,
|
|
327
|
+
method,
|
|
328
|
+
...operationObject,
|
|
329
|
+
});
|
|
330
|
+
});
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
public async genFile() {
|
|
336
|
+
const basePath = this.config.serversPath || "./src/service";
|
|
337
|
+
try {
|
|
338
|
+
const finalPath = join(basePath, this.config.projectName!);
|
|
339
|
+
this.finalPath = finalPath;
|
|
340
|
+
|
|
341
|
+
if (existsSync(finalPath)) {
|
|
342
|
+
for (const name of readdirSync(finalPath)) {
|
|
343
|
+
if (name === "deprecated") continue;
|
|
344
|
+
rimraf.sync(join(finalPath, name));
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
} catch (error) {
|
|
348
|
+
Log(`🚥 serves 生成失败: ${error}`);
|
|
349
|
+
}
|
|
350
|
+
// 生成 ts 类型声明
|
|
351
|
+
await this.genFileFromTemplate("typings.d.ts", "interface", {
|
|
352
|
+
namespace: this.config.namespace,
|
|
353
|
+
nullable: this.config.nullable,
|
|
354
|
+
list: this.getInterfaceTP(),
|
|
355
|
+
disableTypeCheck: false,
|
|
356
|
+
declareType: this.config.declareType || "type",
|
|
357
|
+
equalSymbol: (this.config.declareType || "type") === "type" ? "=" : "",
|
|
358
|
+
});
|
|
359
|
+
// 生成 controller 文件
|
|
360
|
+
const prettierError = [];
|
|
361
|
+
for (const tp of this.getServiceTP()) {
|
|
362
|
+
// console.log("tp", tp);
|
|
363
|
+
|
|
364
|
+
const template = "serviceController";
|
|
365
|
+
const hasError = await this.genFileFromTemplate(this.getFinalFileName(`${tp.className}.ts`), template, {
|
|
366
|
+
namespace: this.config.namespace,
|
|
367
|
+
requestOptionsType: this.config.requestOptionsType,
|
|
368
|
+
requestImportStatement: this.config.requestImportStatement,
|
|
369
|
+
disableTypeCheck: false,
|
|
370
|
+
...tp,
|
|
371
|
+
});
|
|
372
|
+
prettierError.push(hasError);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (prettierError.includes(true)) {
|
|
376
|
+
Log(`🚥 格式化失败,请检查 service 文件内可能存在的语法错误`);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
await this.genFileFromTemplate(`index.ts`, "serviceIndex", {
|
|
380
|
+
list: this.classNameList,
|
|
381
|
+
disableTypeCheck: false,
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
Log(`✅ 成功生成 service 文件`);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
public concatOrNull = (...arrays) => {
|
|
388
|
+
const c = [].concat(...arrays.filter(Array.isArray));
|
|
389
|
+
return c.length > 0 ? c : null;
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
public getFuncationName(data: APIDataType) {
|
|
393
|
+
// 获取路径相同部分
|
|
394
|
+
const pathBasePrefix = this.getBasePrefix(Object.keys(this.openAPIData.paths));
|
|
395
|
+
return this.config.hook && this.config.hook.customFunctionName
|
|
396
|
+
? this.config.hook.customFunctionName(data)
|
|
397
|
+
: data.operationId
|
|
398
|
+
? this.resolveFunctionName(stripDot(data.operationId), data.method)
|
|
399
|
+
: data.method + this.genDefaultFunctionName(data.path, pathBasePrefix);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
public getTypeName(data: APIDataType) {
|
|
403
|
+
const namespace = this.config.namespace ? `${this.config.namespace}.` : "";
|
|
404
|
+
const typeName = this.config?.hook?.customTypeName?.(data) || this.getFuncationName(data);
|
|
405
|
+
|
|
406
|
+
return resolveTypeName(`${namespace}${typeName ?? data.operationId}Params`);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
public getServiceTP() {
|
|
410
|
+
return Object.keys(this.apiData)
|
|
411
|
+
.map((tag, index) => {
|
|
412
|
+
// functionName tag 级别防重
|
|
413
|
+
const tmpFunctionRD: Record<string, number> = {};
|
|
414
|
+
|
|
415
|
+
const genParams = this.apiData[tag]
|
|
416
|
+
.filter(
|
|
417
|
+
api =>
|
|
418
|
+
// 暂不支持变量
|
|
419
|
+
!api.path.includes("${"),
|
|
420
|
+
)
|
|
421
|
+
.map(api => {
|
|
422
|
+
const newApi = api;
|
|
423
|
+
try {
|
|
424
|
+
const allParams = this.getParamsTP(newApi.parameters, newApi.path);
|
|
425
|
+
const body = this.getBodyTP(newApi.requestBody);
|
|
426
|
+
const response = this.getResponseTP(newApi.responses);
|
|
427
|
+
|
|
428
|
+
// let { file, ...params } = allParams || {}; // I dont't know if 'file' is valid parameter, maybe it's safe to remove it
|
|
429
|
+
// const newfile = this.getFileTP(newApi.requestBody);
|
|
430
|
+
// file = this.concatOrNull(file, newfile);
|
|
431
|
+
const params = allParams || {};
|
|
432
|
+
const file = this.getFileTP(newApi.requestBody);
|
|
433
|
+
|
|
434
|
+
let formData = false;
|
|
435
|
+
if ((body && (body.mediaType || "").includes("form-data")) || file) {
|
|
436
|
+
formData = true;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
let functionName = this.getFuncationName(newApi);
|
|
440
|
+
|
|
441
|
+
if (functionName && tmpFunctionRD[functionName]) {
|
|
442
|
+
functionName = `${functionName}_${(tmpFunctionRD[functionName] += 1)}`;
|
|
443
|
+
} else if (functionName) {
|
|
444
|
+
tmpFunctionRD[functionName] = 1;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
let formattedPath = newApi.path.replace(/:([^/]*)|{([^}]*)}/gi, (_, str, str2) => `$\{${str || str2}}`);
|
|
448
|
+
if (newApi.extensions && newApi.extensions["x-antTech-description"]) {
|
|
449
|
+
const { extensions } = newApi;
|
|
450
|
+
const { apiName, antTechVersion, productCode, antTechApiName } = extensions["x-antTech-description"];
|
|
451
|
+
formattedPath = antTechApiName || formattedPath;
|
|
452
|
+
this.mappings.push({
|
|
453
|
+
antTechApi: formattedPath,
|
|
454
|
+
popAction: apiName,
|
|
455
|
+
popProduct: productCode,
|
|
456
|
+
antTechVersion,
|
|
457
|
+
});
|
|
458
|
+
newApi.antTechVersion = antTechVersion;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const finalParams = params;
|
|
462
|
+
|
|
463
|
+
// 处理 query 中的复杂对象
|
|
464
|
+
if (finalParams && finalParams.query) {
|
|
465
|
+
finalParams.query = finalParams.query.map(ele => ({
|
|
466
|
+
...ele,
|
|
467
|
+
isComplexType: ele.isObject,
|
|
468
|
+
}));
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const getPrefixPath = () => {
|
|
472
|
+
if (!this.config.apiPrefix) {
|
|
473
|
+
return formattedPath;
|
|
474
|
+
}
|
|
475
|
+
// 静态 apiPrefix
|
|
476
|
+
const prefix =
|
|
477
|
+
typeof this.config.apiPrefix === "function"
|
|
478
|
+
? `${this.config.apiPrefix({
|
|
479
|
+
path: formattedPath,
|
|
480
|
+
method: newApi.method,
|
|
481
|
+
namespace: tag,
|
|
482
|
+
functionName,
|
|
483
|
+
})}`.trim()
|
|
484
|
+
: this.config.apiPrefix.trim();
|
|
485
|
+
|
|
486
|
+
if (!prefix) {
|
|
487
|
+
return formattedPath;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
if (prefix.startsWith("'") || prefix.startsWith('"') || prefix.startsWith("`")) {
|
|
491
|
+
const finalPrefix = prefix.slice(1, prefix.length - 1);
|
|
492
|
+
if (formattedPath.startsWith(finalPrefix) || formattedPath.startsWith(`/${finalPrefix}`)) {
|
|
493
|
+
return formattedPath;
|
|
494
|
+
}
|
|
495
|
+
return `${finalPrefix}${formattedPath}`;
|
|
496
|
+
}
|
|
497
|
+
// prefix 变量
|
|
498
|
+
return `/${prefix}${formattedPath}`;
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
return {
|
|
502
|
+
...newApi,
|
|
503
|
+
functionName: this.config.isCamelCase ? camelCase(functionName) : functionName,
|
|
504
|
+
typeName: this.getTypeName(newApi),
|
|
505
|
+
path: getPrefixPath(),
|
|
506
|
+
pathInComment: formattedPath.replace(/\*/g, "*"),
|
|
507
|
+
hasPathVariables: formattedPath.includes("{"),
|
|
508
|
+
hasApiPrefix: !!this.config.apiPrefix,
|
|
509
|
+
method: newApi.method,
|
|
510
|
+
// 如果 functionName 和 summary 相同,则不显示 summary
|
|
511
|
+
desc:
|
|
512
|
+
functionName === newApi.summary
|
|
513
|
+
? newApi.description
|
|
514
|
+
: [
|
|
515
|
+
newApi.summary,
|
|
516
|
+
newApi.description,
|
|
517
|
+
(newApi.responses?.default as ResponseObject)?.description
|
|
518
|
+
? `返回值: ${(newApi.responses?.default as ResponseObject).description}`
|
|
519
|
+
: "",
|
|
520
|
+
]
|
|
521
|
+
.filter(s => s)
|
|
522
|
+
.join(" "),
|
|
523
|
+
hasHeader: !!(params && params.header) || !!(body && body.mediaType),
|
|
524
|
+
params: finalParams,
|
|
525
|
+
hasParams: Boolean(Object.keys(finalParams || {}).length),
|
|
526
|
+
options: this.config.hook?.customOptionsDefaultValue?.(newApi) || {},
|
|
527
|
+
body,
|
|
528
|
+
file,
|
|
529
|
+
hasFormData: formData,
|
|
530
|
+
response,
|
|
531
|
+
};
|
|
532
|
+
} catch (error) {
|
|
533
|
+
// eslint-disable-next-line no-console
|
|
534
|
+
console.error("[GenSDK] gen service param error:", error);
|
|
535
|
+
throw error;
|
|
536
|
+
}
|
|
537
|
+
})
|
|
538
|
+
// 排序下,要不每次git都乱了
|
|
539
|
+
.sort((a, b) => a.path.localeCompare(b.path));
|
|
540
|
+
|
|
541
|
+
const fileName = this.replaceDot(tag) || `api${index}`;
|
|
542
|
+
|
|
543
|
+
let className = fileName;
|
|
544
|
+
if (this.config.hook && this.config.hook.customClassName) {
|
|
545
|
+
className = this.config.hook.customClassName(tag);
|
|
546
|
+
}
|
|
547
|
+
if (genParams.length) {
|
|
548
|
+
this.classNameList.push({
|
|
549
|
+
fileName: className,
|
|
550
|
+
controllerName: className,
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
return {
|
|
554
|
+
genType: "ts",
|
|
555
|
+
className,
|
|
556
|
+
instanceName: `${fileName[0]?.toLowerCase()}${fileName.substr(1)}`,
|
|
557
|
+
list: genParams,
|
|
558
|
+
};
|
|
559
|
+
})
|
|
560
|
+
.filter(ele => !!ele?.list?.length);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
public getBodyTP(requestBody: any = {}) {
|
|
564
|
+
const reqBody: RequestBodyObject = this.resolveRefObject(requestBody);
|
|
565
|
+
if (!reqBody) {
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
const reqContent: ContentObject = reqBody.content;
|
|
569
|
+
if (typeof reqContent !== "object" || (reqContent && Object.keys(reqContent).length === 0)) {
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
let mediaType = Object.keys(reqContent)[0];
|
|
573
|
+
|
|
574
|
+
const schema: SchemaObject = reqContent[mediaType].schema || DEFAULT_SCHEMA;
|
|
575
|
+
|
|
576
|
+
if (mediaType === "*/*") {
|
|
577
|
+
mediaType = "";
|
|
578
|
+
}
|
|
579
|
+
// 如果 requestBody 有 required 属性,则正常展示;如果没有,默认非必填
|
|
580
|
+
const required = typeof requestBody.required === "boolean" ? requestBody.required : false;
|
|
581
|
+
if (schema.type === "object" && schema.properties) {
|
|
582
|
+
const propertiesList = Object.keys(schema.properties)
|
|
583
|
+
.map(p => {
|
|
584
|
+
if (
|
|
585
|
+
schema.properties &&
|
|
586
|
+
schema.properties[p] &&
|
|
587
|
+
!["binary", "base64"].includes((schema.properties[p] as SchemaObject).format || "") &&
|
|
588
|
+
!(
|
|
589
|
+
["string[]", "array"].includes((schema.properties[p] as SchemaObject).type || "") &&
|
|
590
|
+
["binary", "base64"].includes(((schema.properties[p] as SchemaObject).items as SchemaObject).format || "")
|
|
591
|
+
)
|
|
592
|
+
) {
|
|
593
|
+
return {
|
|
594
|
+
key: p,
|
|
595
|
+
schema: {
|
|
596
|
+
...schema.properties[p],
|
|
597
|
+
type: this.getType(schema.properties[p], this.config.namespace),
|
|
598
|
+
required: schema.required?.includes(p) ?? false,
|
|
599
|
+
},
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
return undefined;
|
|
603
|
+
})
|
|
604
|
+
.filter(p => p);
|
|
605
|
+
return {
|
|
606
|
+
mediaType,
|
|
607
|
+
...schema,
|
|
608
|
+
required,
|
|
609
|
+
propertiesList,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
return {
|
|
613
|
+
mediaType,
|
|
614
|
+
required,
|
|
615
|
+
type: this.getType(schema, this.config.namespace),
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
public getFileTP(requestBody: any = {}) {
|
|
619
|
+
const reqBody: RequestBodyObject = this.resolveRefObject(requestBody);
|
|
620
|
+
if (reqBody && reqBody.content && reqBody.content["multipart/form-data"]) {
|
|
621
|
+
const ret = this.resolveFileTP(reqBody.content["multipart/form-data"].schema);
|
|
622
|
+
return ret.length > 0 ? ret : null;
|
|
623
|
+
}
|
|
624
|
+
return null;
|
|
625
|
+
}
|
|
626
|
+
public resolveFileTP(obj: any) {
|
|
627
|
+
let ret = [];
|
|
628
|
+
const resolved = this.resolveObject(obj);
|
|
629
|
+
const props =
|
|
630
|
+
(resolved.props &&
|
|
631
|
+
resolved.props.length > 0 &&
|
|
632
|
+
resolved.props[0].filter(
|
|
633
|
+
p =>
|
|
634
|
+
p.format === "binary" ||
|
|
635
|
+
p.format === "base64" ||
|
|
636
|
+
((p.type === "string[]" || p.type === "array") &&
|
|
637
|
+
(p.items.format === "binary" || p.items.format === "base64")),
|
|
638
|
+
)) ||
|
|
639
|
+
[];
|
|
640
|
+
if (props.length > 0) {
|
|
641
|
+
ret = props.map(p => {
|
|
642
|
+
return { title: p.name, multiple: p.type === "string[]" || p.type === "array" };
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
if (resolved.type) ret = [...ret, ...this.resolveFileTP(resolved.type)];
|
|
646
|
+
return ret;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
public getResponseTP(responses: ResponsesObject = {}) {
|
|
650
|
+
const { components } = this.openAPIData;
|
|
651
|
+
const response: ResponseObject | undefined =
|
|
652
|
+
responses && this.resolveRefObject(responses.default || responses["200"] || responses["201"]);
|
|
653
|
+
const defaultResponse = {
|
|
654
|
+
mediaType: "*/*",
|
|
655
|
+
type: "any",
|
|
656
|
+
};
|
|
657
|
+
if (!response) {
|
|
658
|
+
return defaultResponse;
|
|
659
|
+
}
|
|
660
|
+
const resContent: ContentObject | undefined = response.content;
|
|
661
|
+
const resContentMediaTypes = Object.keys(resContent || {});
|
|
662
|
+
const mediaType = resContentMediaTypes.includes("application/json") ? "application/json" : resContentMediaTypes[0]; // 优先使用 application/json
|
|
663
|
+
if (typeof resContent !== "object" || !mediaType) {
|
|
664
|
+
return defaultResponse;
|
|
665
|
+
}
|
|
666
|
+
let schema = (resContent[mediaType].schema || DEFAULT_SCHEMA) as SchemaObject;
|
|
667
|
+
|
|
668
|
+
if (schema.$ref) {
|
|
669
|
+
const refPaths = schema.$ref.split("/");
|
|
670
|
+
const refName = refPaths[refPaths.length - 1];
|
|
671
|
+
const childrenSchema = components.schemas[refName] as SchemaObject;
|
|
672
|
+
if (childrenSchema?.type === "object" && "properties" in childrenSchema && this.config.dataFields) {
|
|
673
|
+
schema =
|
|
674
|
+
this.config.dataFields.map(field => childrenSchema.properties[field]).filter(Boolean)?.[0] ||
|
|
675
|
+
resContent[mediaType].schema ||
|
|
676
|
+
DEFAULT_SCHEMA;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
if ("properties" in schema) {
|
|
681
|
+
Object.keys(schema.properties).map(fieldName => {
|
|
682
|
+
// eslint-disable-next-line @typescript-eslint/dot-notation
|
|
683
|
+
schema.properties[fieldName]["required"] = schema.required?.includes(fieldName) ?? false;
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
return {
|
|
687
|
+
mediaType,
|
|
688
|
+
type: this.getType(schema, this.config.namespace),
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
public getParamsTP(
|
|
693
|
+
parameters: (ParameterObject | ReferenceObject)[] = [],
|
|
694
|
+
path: string = null,
|
|
695
|
+
): Record<string, ParameterObject[]> {
|
|
696
|
+
const templateParams: Record<string, ParameterObject[]> = {};
|
|
697
|
+
|
|
698
|
+
if (parameters && parameters.length) {
|
|
699
|
+
["query", "path", "cookie" /* , 'file' */].forEach(source => {
|
|
700
|
+
// Possible values are "query", "header", "path" or "cookie". (https://swagger.io/specification/)
|
|
701
|
+
const params = parameters
|
|
702
|
+
.map(p => this.resolveRefObject(p))
|
|
703
|
+
.filter((p: ParameterObject) => p.in === source)
|
|
704
|
+
.map(p => {
|
|
705
|
+
const isDirectObject = ((p.schema || {}).type || p.type) === "object";
|
|
706
|
+
const refList = ((p.schema || {}).$ref || p.$ref || "").split("/");
|
|
707
|
+
const ref = refList[refList.length - 1];
|
|
708
|
+
const deRefObj = (Object.entries(
|
|
709
|
+
(this.openAPIData.components && this.openAPIData.components.schemas) || {},
|
|
710
|
+
).find(([k]) => k === ref) || []) as any;
|
|
711
|
+
const isRefObject = (deRefObj[1] || {}).type === "object";
|
|
712
|
+
return {
|
|
713
|
+
...p,
|
|
714
|
+
isObject: isDirectObject || isRefObject,
|
|
715
|
+
type: this.getType(p.schema || DEFAULT_SCHEMA, this.config.namespace),
|
|
716
|
+
};
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
if (params.length) {
|
|
720
|
+
templateParams[source] = params;
|
|
721
|
+
}
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
if (path && path.length > 0) {
|
|
726
|
+
const regex = /\{(\w+)\}/g;
|
|
727
|
+
templateParams.path = templateParams.path || [];
|
|
728
|
+
let match = null;
|
|
729
|
+
while ((match = regex.exec(path))) {
|
|
730
|
+
if (!templateParams.path.some(p => p.name === match[1])) {
|
|
731
|
+
templateParams.path.push({
|
|
732
|
+
...DEFAULT_PATH_PARAM,
|
|
733
|
+
name: match[1],
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// 如果 path 没有内容,则将删除 path 参数,避免影响后续的 hasParams 判断
|
|
739
|
+
if (!templateParams.path.length) delete templateParams.path;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
return templateParams;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
private collectRefs(obj: any, refs: Set<string>) {
|
|
746
|
+
if (!obj || typeof obj !== "object") return;
|
|
747
|
+
if (obj.$ref) {
|
|
748
|
+
const refName = obj.$ref.replace("#/components/schemas/", "");
|
|
749
|
+
if (!refs.has(refName)) {
|
|
750
|
+
refs.add(refName);
|
|
751
|
+
const { components } = this.openAPIData;
|
|
752
|
+
if (components?.schemas?.[refName]) {
|
|
753
|
+
this.collectRefs(components.schemas[refName], refs);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
for (const value of Object.values(obj)) {
|
|
759
|
+
this.collectRefs(value, refs);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
public getInterfaceTP() {
|
|
764
|
+
const { components } = this.openAPIData;
|
|
765
|
+
const specifiedPaths = this.config.specifiedPaths;
|
|
766
|
+
const isIncremental = !!specifiedPaths?.length;
|
|
767
|
+
|
|
768
|
+
let usedSchemas: Set<string> | null = null;
|
|
769
|
+
if (isIncremental) {
|
|
770
|
+
usedSchemas = new Set<string>();
|
|
771
|
+
specifiedPaths!.forEach(p => {
|
|
772
|
+
const pathItem = this.openAPIData.paths?.[p];
|
|
773
|
+
if (pathItem) this.collectRefs(pathItem, usedSchemas!);
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const data =
|
|
778
|
+
components &&
|
|
779
|
+
components.schemas &&
|
|
780
|
+
[components.schemas].map(defines => {
|
|
781
|
+
if (!defines) {
|
|
782
|
+
return null;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
const typeNames = Object.keys(defines).filter(typeName => !usedSchemas || usedSchemas.has(typeName));
|
|
786
|
+
|
|
787
|
+
return typeNames.map(typeName => {
|
|
788
|
+
const result = this.resolveObject(defines[typeName]);
|
|
789
|
+
|
|
790
|
+
const getDefinesType = () => {
|
|
791
|
+
if (result.type) {
|
|
792
|
+
return (defines[typeName] as SchemaObject).type === "object" || result.type;
|
|
793
|
+
}
|
|
794
|
+
return "Record<string, any>";
|
|
795
|
+
};
|
|
796
|
+
return {
|
|
797
|
+
typeName: resolveTypeName(typeName),
|
|
798
|
+
type: getDefinesType(),
|
|
799
|
+
parent: result.parent,
|
|
800
|
+
props: result.props || [],
|
|
801
|
+
isEnum: result.isEnum,
|
|
802
|
+
};
|
|
803
|
+
});
|
|
804
|
+
});
|
|
805
|
+
|
|
806
|
+
// 强行替换掉请求参数params的类型,生成方法对应的 xxxxParams 类型
|
|
807
|
+
const allPaths = Object.keys(this.openAPIData.paths || {});
|
|
808
|
+
const filteredPaths = specifiedPaths?.length ? allPaths.filter(p => specifiedPaths.includes(p)) : allPaths;
|
|
809
|
+
|
|
810
|
+
filteredPaths.forEach(p => {
|
|
811
|
+
const pathItem: PathItemObject = this.openAPIData.paths[p];
|
|
812
|
+
["get", "put", "post", "delete", "patch"].forEach(method => {
|
|
813
|
+
const operationObject: OperationObject = pathItem[method];
|
|
814
|
+
if (!operationObject) {
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
operationObject.parameters = operationObject.parameters?.filter(
|
|
818
|
+
item => (item as ParameterObject)?.in !== "header",
|
|
819
|
+
);
|
|
820
|
+
const props = [];
|
|
821
|
+
if (operationObject.parameters) {
|
|
822
|
+
operationObject.parameters.forEach((parameter: any) => {
|
|
823
|
+
props.push({
|
|
824
|
+
desc: parameter.description ?? "",
|
|
825
|
+
name: parameter.name,
|
|
826
|
+
required: parameter.required,
|
|
827
|
+
type: this.getType(parameter.schema),
|
|
828
|
+
});
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
// parameters may be in path
|
|
832
|
+
if (pathItem.parameters) {
|
|
833
|
+
pathItem.parameters.forEach((parameter: any) => {
|
|
834
|
+
props.push({
|
|
835
|
+
desc: parameter.description ?? "",
|
|
836
|
+
name: parameter.name,
|
|
837
|
+
required: parameter.required,
|
|
838
|
+
type: this.getType(parameter.schema),
|
|
839
|
+
});
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
if (props.length > 0 && data) {
|
|
844
|
+
data.push([
|
|
845
|
+
{
|
|
846
|
+
typeName: this.getTypeName({ ...operationObject, method, path: p }),
|
|
847
|
+
type: "Record<string, any>",
|
|
848
|
+
parent: undefined,
|
|
849
|
+
props: [props],
|
|
850
|
+
isEnum: false,
|
|
851
|
+
},
|
|
852
|
+
]);
|
|
853
|
+
}
|
|
854
|
+
});
|
|
855
|
+
});
|
|
856
|
+
// ---- 生成 xxxparams 类型 end---------
|
|
857
|
+
|
|
858
|
+
return (
|
|
859
|
+
data &&
|
|
860
|
+
data
|
|
861
|
+
.reduce((p, c) => p && c && p.concat(c), [])
|
|
862
|
+
// 排序下,要不每次git都乱了
|
|
863
|
+
.sort((a, b) => a.typeName.localeCompare(b.typeName))
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
private async genFileFromTemplate(
|
|
868
|
+
fileName: string,
|
|
869
|
+
type: TypescriptFileType,
|
|
870
|
+
params: Record<string, any>,
|
|
871
|
+
): Promise<boolean> {
|
|
872
|
+
try {
|
|
873
|
+
const template = this.getTemplate(type);
|
|
874
|
+
// 设置输出不转义
|
|
875
|
+
nunjucks.configure({
|
|
876
|
+
autoescape: false,
|
|
877
|
+
});
|
|
878
|
+
return await writeFile(this.finalPath, fileName, nunjucks.renderString(template, params));
|
|
879
|
+
} catch (error) {
|
|
880
|
+
// eslint-disable-next-line no-console
|
|
881
|
+
console.error("[GenSDK] file gen fail:", fileName, "type:", type);
|
|
882
|
+
throw error;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
private getTemplate(type: "interface" | "serviceController" | "serviceIndex"): string {
|
|
887
|
+
return readFileSync(join(this.config.templatesFolder, `${type}.njk`), "utf8");
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// 获取 TS 类型的属性列表
|
|
891
|
+
getProps(schemaObject: SchemaObject) {
|
|
892
|
+
const requiredPropKeys = schemaObject?.required ?? false;
|
|
893
|
+
return schemaObject.properties
|
|
894
|
+
? Object.keys(schemaObject.properties).map(propName => {
|
|
895
|
+
const schema: SchemaObject = (schemaObject.properties && schemaObject.properties[propName]) || DEFAULT_SCHEMA;
|
|
896
|
+
// 剔除属性键值中的特殊符号,因为函数入参变量存在特殊符号会导致解析文件失败
|
|
897
|
+
return {
|
|
898
|
+
...schema,
|
|
899
|
+
name: propName,
|
|
900
|
+
type: this.getType(schema),
|
|
901
|
+
desc: [schema.title, schema.description].filter(s => s).join(" "),
|
|
902
|
+
// 如果没有 required 信息,默认全部是非必填
|
|
903
|
+
required: requiredPropKeys ? requiredPropKeys.some(key => key === propName) : false,
|
|
904
|
+
};
|
|
905
|
+
})
|
|
906
|
+
: [];
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
getType(schemaObject: SchemaObject | undefined, namespace?: string) {
|
|
910
|
+
const hookFunc = this.config.hook?.customType;
|
|
911
|
+
if (hookFunc) {
|
|
912
|
+
const type = hookFunc(schemaObject, namespace, defaultGetType);
|
|
913
|
+
if (typeof type === "string") {
|
|
914
|
+
return type;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return defaultGetType(schemaObject, namespace);
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
resolveObject(schemaObject: SchemaObject) {
|
|
921
|
+
schemaObject = schemaObject ?? {};
|
|
922
|
+
// 引用类型
|
|
923
|
+
if (schemaObject.$ref) {
|
|
924
|
+
return this.resolveRefObject(schemaObject);
|
|
925
|
+
}
|
|
926
|
+
// 枚举类型
|
|
927
|
+
if (schemaObject.enum) {
|
|
928
|
+
return this.resolveEnumObject(schemaObject);
|
|
929
|
+
}
|
|
930
|
+
// 继承类型
|
|
931
|
+
if (schemaObject.allOf && schemaObject.allOf.length) {
|
|
932
|
+
return this.resolveAllOfObject(schemaObject);
|
|
933
|
+
}
|
|
934
|
+
// 对象类型
|
|
935
|
+
if (schemaObject.properties) {
|
|
936
|
+
return this.resolveProperties(schemaObject);
|
|
937
|
+
}
|
|
938
|
+
// 数组类型
|
|
939
|
+
if (schemaObject.items && schemaObject.type === "array") {
|
|
940
|
+
return this.resolveArray(schemaObject);
|
|
941
|
+
}
|
|
942
|
+
return schemaObject;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
resolveArray(schemaObject: SchemaObject) {
|
|
946
|
+
if (schemaObject.items.$ref) {
|
|
947
|
+
const refObj = schemaObject.items.$ref.split("/");
|
|
948
|
+
return {
|
|
949
|
+
type: `${refObj[refObj.length - 1]}[]`,
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
// TODO: 这里需要解析出具体属性,但由于 parser 层还不确定,所以暂时先返回 any
|
|
953
|
+
return "any[]";
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
resolveProperties(schemaObject: SchemaObject) {
|
|
957
|
+
return {
|
|
958
|
+
props: [this.getProps(schemaObject)],
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
resolveEnumObject(schemaObject: SchemaObject) {
|
|
963
|
+
const enumArray = schemaObject.enum;
|
|
964
|
+
|
|
965
|
+
let enumStr;
|
|
966
|
+
switch (this.config.enumStyle) {
|
|
967
|
+
case "enum":
|
|
968
|
+
enumStr = `{${enumArray.map(v => `${v}="${v}"`).join(",")}}`;
|
|
969
|
+
break;
|
|
970
|
+
case "string-literal":
|
|
971
|
+
enumStr = Array.from(
|
|
972
|
+
new Set(enumArray.map(v => (typeof v === "string" ? `"${v.replace(/"/g, '"')}"` : this.getType(v)))),
|
|
973
|
+
).join(" | ");
|
|
974
|
+
break;
|
|
975
|
+
default:
|
|
976
|
+
break;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
return {
|
|
980
|
+
isEnum: this.config.enumStyle == "enum",
|
|
981
|
+
type: Array.isArray(enumArray) ? enumStr : "string",
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
resolveAllOfObject(schemaObject: SchemaObject) {
|
|
986
|
+
const props = (schemaObject.allOf || []).map(item =>
|
|
987
|
+
item.$ref ? [{ ...item, type: this.getType(item).split("/").pop() }] : this.getProps(item),
|
|
988
|
+
);
|
|
989
|
+
|
|
990
|
+
if (schemaObject.properties) {
|
|
991
|
+
const extProps = this.getProps(schemaObject);
|
|
992
|
+
return { props: [...props, extProps] };
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
return { props };
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// 将地址path路径转为大驼峰
|
|
999
|
+
private genDefaultFunctionName(path: string, pathBasePrefix: string) {
|
|
1000
|
+
// 首字母转大写
|
|
1001
|
+
function toUpperFirstLetter(text: string) {
|
|
1002
|
+
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
return path
|
|
1006
|
+
?.replace(pathBasePrefix, "")
|
|
1007
|
+
.split("/")
|
|
1008
|
+
.map(str => {
|
|
1009
|
+
/**
|
|
1010
|
+
* 兼容错误命名如 /user/:id/:name
|
|
1011
|
+
* 因为是typeName,所以直接进行转换
|
|
1012
|
+
* */
|
|
1013
|
+
let s = resolveTypeName(str);
|
|
1014
|
+
if (s.includes("-")) {
|
|
1015
|
+
s = s.replace(/(-\w)+/g, (_match: string, p1) => p1?.slice(1).toUpperCase());
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
if (s.match(/^{.+}$/gim)) {
|
|
1019
|
+
return `By${toUpperFirstLetter(s.slice(1, s.length - 1))}`;
|
|
1020
|
+
}
|
|
1021
|
+
return toUpperFirstLetter(s);
|
|
1022
|
+
})
|
|
1023
|
+
.join("");
|
|
1024
|
+
}
|
|
1025
|
+
// 检测所有path重复区域(prefix)
|
|
1026
|
+
private getBasePrefix(paths: string[]) {
|
|
1027
|
+
const arr = [];
|
|
1028
|
+
paths
|
|
1029
|
+
.map(item => item.split("/"))
|
|
1030
|
+
.forEach(pathItem => {
|
|
1031
|
+
pathItem.forEach((item, key) => {
|
|
1032
|
+
if (arr.length <= key) {
|
|
1033
|
+
arr[key] = [];
|
|
1034
|
+
}
|
|
1035
|
+
arr[key].push(item);
|
|
1036
|
+
});
|
|
1037
|
+
});
|
|
1038
|
+
|
|
1039
|
+
const res = [];
|
|
1040
|
+
arr
|
|
1041
|
+
.map(item => Array.from(new Set(item)))
|
|
1042
|
+
.every(item => {
|
|
1043
|
+
const b = item.length === 1;
|
|
1044
|
+
if (b) {
|
|
1045
|
+
res.push(item);
|
|
1046
|
+
}
|
|
1047
|
+
return b;
|
|
1048
|
+
});
|
|
1049
|
+
|
|
1050
|
+
return `${res.join("/")}/`;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
private resolveRefObject(refObject: any): any {
|
|
1054
|
+
if (!refObject || !refObject.$ref) {
|
|
1055
|
+
return refObject;
|
|
1056
|
+
}
|
|
1057
|
+
const refPaths = refObject.$ref.split("/");
|
|
1058
|
+
if (refPaths[0] === "#") {
|
|
1059
|
+
refPaths.shift();
|
|
1060
|
+
let obj: any = this.openAPIData;
|
|
1061
|
+
refPaths.forEach((node: any) => {
|
|
1062
|
+
obj = obj[node];
|
|
1063
|
+
});
|
|
1064
|
+
if (!obj) {
|
|
1065
|
+
throw new Error(`[GenSDK] Data Error! Notfoud: ${refObject.$ref}`);
|
|
1066
|
+
}
|
|
1067
|
+
return {
|
|
1068
|
+
...this.resolveRefObject(obj),
|
|
1069
|
+
type: obj.$ref ? this.resolveRefObject(obj).type : obj,
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
return refObject;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
private getFinalFileName(s: string): string {
|
|
1076
|
+
// 支持下划线、中划线和空格分隔符,注意分隔符枚举值的顺序不能改变,否则正则匹配会报错
|
|
1077
|
+
return s.replace(/[-_ ](\w)/g, (_all, letter) => letter.toUpperCase());
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
private replaceDot(s: string) {
|
|
1081
|
+
return s.replace(/\./g, "_").replace(/[-_ ](\w)/g, (_all, letter) => letter.toUpperCase());
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
private resolveFunctionName(functionName: string, methodName) {
|
|
1085
|
+
// 类型声明过滤关键字
|
|
1086
|
+
if (ReservedDict.check(functionName)) {
|
|
1087
|
+
return `${functionName}Using${methodName.toUpperCase()}`;
|
|
1088
|
+
}
|
|
1089
|
+
return functionName;
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
export { ServiceGenerator };
|