@dazhicheng/openapi 1.0.0 → 1.1.0
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 +7 -0
- package/dist/cli.d.ts +2 -0
- package/dist/index.d.ts +135 -0
- package/dist/index.esm.js +2 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/log.d.ts +2 -0
- package/dist/mockGenerator.d.ts +8 -0
- package/dist/openAPIParserMock/index.d.ts +7 -0
- package/dist/openAPIParserMock/primitives.d.ts +31 -0
- package/dist/openAPIParserMock/utils.d.ts +8 -0
- package/dist/serviceGenerator.d.ts +478 -0
- package/dist/util.d.ts +35 -0
- package/package.json +41 -4
- package/src/cli.ts +24 -104
- package/src/index.ts +251 -0
- package/src/log.ts +6 -0
- package/src/mockGenerator.ts +239 -0
- package/src/openAPIParserMock/index.ts +254 -0
- package/src/openAPIParserMock/primitives.ts +30 -0
- package/src/openAPIParserMock/utils.ts +54 -0
- package/src/serviceGenerator.ts +1065 -0
- package/src/typings.d.ts +6 -0
- package/src/util.ts +203 -0
- package/templates/interface.njk +54 -0
- package/templates/serviceController.njk +38 -0
- package/templates/serviceIndex.njk +14 -0
- package/tsconfig.json +2 -1
- package/openapi.config.ts +0 -16
- package/src/discovery.ts +0 -44
- package/src/fetcher.ts +0 -19
- package/src/formatter.ts +0 -16
- package/src/generator.ts +0 -187
- package/src/parser.ts +0 -336
- package/src/types.ts +0 -91
package/src/cli.ts
CHANGED
|
@@ -1,108 +1,28 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
async function main() {
|
|
23
|
-
console.log("🚀 开始生成 OpenAPI TypeScript 接口...\n");
|
|
24
|
-
|
|
25
|
-
const config = await loadConfig();
|
|
26
|
-
const { outputDir, requestImportPath, requestFnName = "request" } = config;
|
|
27
|
-
|
|
28
|
-
let services: ServiceConfig[];
|
|
29
|
-
|
|
30
|
-
if (config.gateway) {
|
|
31
|
-
console.log(`🔍 正在从网关自动发现服务: ${config.gateway}`);
|
|
32
|
-
services = await discoverServices(config.gateway);
|
|
33
|
-
console.log(` 发现 ${services.length} 个服务\n`);
|
|
34
|
-
} else if (config.services && config.services.length > 0) {
|
|
35
|
-
services = config.services;
|
|
36
|
-
} else {
|
|
37
|
-
console.warn("⚠️ 未配置任何 service 或 gateway,请编辑 openapi.config.ts");
|
|
38
|
-
return;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const outDir = resolve(ROOT, outputDir);
|
|
42
|
-
if (!existsSync(outDir)) {
|
|
43
|
-
mkdirSync(outDir, { recursive: true });
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
let successCount = 0;
|
|
47
|
-
let failCount = 0;
|
|
48
|
-
const generatedNames: string[] = [];
|
|
49
|
-
|
|
50
|
-
for (const service of services) {
|
|
51
|
-
try {
|
|
52
|
-
console.log(`📡 [${service.name}] 获取文档: ${service.url}`);
|
|
53
|
-
const doc = await fetchSwaggerDoc(service.url);
|
|
54
|
-
|
|
55
|
-
console.log(`🔍 [${service.name}] 解析中...`);
|
|
56
|
-
const parsed = parseSwaggerDoc(doc, {
|
|
57
|
-
pathPrefix: service.pathPrefix,
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
console.log(` ├─ ${parsed.interfaces.length} 个类型定义`);
|
|
61
|
-
console.log(` └─ ${parsed.apis.length} 个 API 接口`);
|
|
62
|
-
|
|
63
|
-
const code = generateServiceFile(parsed, {
|
|
64
|
-
requestImportPath,
|
|
65
|
-
requestFnName,
|
|
66
|
-
serviceName: service.name,
|
|
67
|
-
serviceDescription: service.description,
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
const formatted = await formatTypeScript(code);
|
|
71
|
-
|
|
72
|
-
const outFile = resolve(outDir, `${service.name}.ts`);
|
|
73
|
-
writeFileSync(outFile, formatted, "utf-8");
|
|
74
|
-
console.log(`✅ [${service.name}] -> ${outFile}\n`);
|
|
75
|
-
successCount++;
|
|
76
|
-
generatedNames.push(service.name);
|
|
77
|
-
} catch (err) {
|
|
78
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
79
|
-
console.error(`❌ [${service.name}] 失败: ${msg}\n`);
|
|
80
|
-
failCount++;
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import chalk from "chalk";
|
|
4
|
+
import { cosmiconfigSync } from "cosmiconfig";
|
|
5
|
+
import { generateService, GenerateServiceProps } from "./index";
|
|
6
|
+
|
|
7
|
+
const explorerSync = cosmiconfigSync("openapi2ts");
|
|
8
|
+
const searchedFor = explorerSync.search();
|
|
9
|
+
|
|
10
|
+
async function run() {
|
|
11
|
+
try {
|
|
12
|
+
if (searchedFor?.config) {
|
|
13
|
+
const configs: GenerateServiceProps[] = Array.isArray(searchedFor.config)
|
|
14
|
+
? searchedFor.config
|
|
15
|
+
: [searchedFor.config];
|
|
16
|
+
|
|
17
|
+
for (const config of configs) {
|
|
18
|
+
await generateService(config);
|
|
19
|
+
}
|
|
20
|
+
} else {
|
|
21
|
+
throw new Error("config is not found");
|
|
81
22
|
}
|
|
23
|
+
} catch (error) {
|
|
24
|
+
console.log(chalk.red(error));
|
|
82
25
|
}
|
|
83
|
-
|
|
84
|
-
if (generatedNames.length > 0) {
|
|
85
|
-
generateIndexFile(outDir, generatedNames);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
console.log("━".repeat(50));
|
|
89
|
-
console.log(`🎉 生成完毕! 成功: ${successCount}, 失败: ${failCount}`);
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function generateIndexFile(outDir: string, serviceNames: string[]) {
|
|
93
|
-
const lines = ["// 此文件由 @dazhicheng/openapi 自动生成,请勿手动修改", ""];
|
|
94
|
-
|
|
95
|
-
for (const name of serviceNames) {
|
|
96
|
-
lines.push(`export * from './${name}';`);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
lines.push("");
|
|
100
|
-
|
|
101
|
-
const indexFile = resolve(outDir, "index.ts");
|
|
102
|
-
writeFileSync(indexFile, lines.join("\n"), "utf-8");
|
|
103
26
|
}
|
|
104
27
|
|
|
105
|
-
|
|
106
|
-
console.error("生成过程发生错误:", err);
|
|
107
|
-
process.exit(1);
|
|
108
|
-
});
|
|
28
|
+
run();
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import http from "http";
|
|
3
|
+
import https from "https";
|
|
4
|
+
import fetch from "node-fetch";
|
|
5
|
+
import type { OpenAPIObject, OperationObject, SchemaObject } from "openapi3-ts";
|
|
6
|
+
import converter from "swagger2openapi";
|
|
7
|
+
import Log from "./log";
|
|
8
|
+
import { mockGenerator } from "./mockGenerator";
|
|
9
|
+
import { ServiceGenerator } from "./serviceGenerator";
|
|
10
|
+
import type { APIDataType } from "./serviceGenerator";
|
|
11
|
+
|
|
12
|
+
const getImportStatement = (requestLibPath: string) => {
|
|
13
|
+
if (requestLibPath && requestLibPath.startsWith("import")) {
|
|
14
|
+
return requestLibPath;
|
|
15
|
+
}
|
|
16
|
+
if (requestLibPath) {
|
|
17
|
+
return `import request from '${requestLibPath}'`;
|
|
18
|
+
}
|
|
19
|
+
return `import { request } from "umi"`;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type GenerateServiceProps = {
|
|
23
|
+
requestLibPath?: string;
|
|
24
|
+
requestOptionsType?: string;
|
|
25
|
+
requestImportStatement?: string;
|
|
26
|
+
// interface 类型声明方式, 满足某些团队的开发规范
|
|
27
|
+
declareType?: "type" | "interface";
|
|
28
|
+
/**
|
|
29
|
+
* api 的前缀
|
|
30
|
+
*/
|
|
31
|
+
apiPrefix?:
|
|
32
|
+
| string
|
|
33
|
+
| ((params: {
|
|
34
|
+
path: string;
|
|
35
|
+
method: string;
|
|
36
|
+
namespace: string;
|
|
37
|
+
functionName: string;
|
|
38
|
+
autoExclude?: boolean;
|
|
39
|
+
}) => string);
|
|
40
|
+
/**
|
|
41
|
+
* 生成的文件夹的路径
|
|
42
|
+
*/
|
|
43
|
+
serversPath?: string;
|
|
44
|
+
/**
|
|
45
|
+
* Swagger 2.0 或 OpenAPI 3.0 的地址
|
|
46
|
+
*/
|
|
47
|
+
schemaPath?: string;
|
|
48
|
+
/**
|
|
49
|
+
* 项目名称
|
|
50
|
+
*/
|
|
51
|
+
projectName?: string;
|
|
52
|
+
/**
|
|
53
|
+
* 文档登录凭证
|
|
54
|
+
*/
|
|
55
|
+
authorization?: string;
|
|
56
|
+
|
|
57
|
+
hook?: {
|
|
58
|
+
/** change open api data after constructor */
|
|
59
|
+
afterOpenApiDataInited?: (openAPIData: OpenAPIObject) => OpenAPIObject;
|
|
60
|
+
|
|
61
|
+
/** 自定义函数名称 */
|
|
62
|
+
customFunctionName?: (data: APIDataType) => string;
|
|
63
|
+
/** 自定义类型名称 */
|
|
64
|
+
customTypeName?: (data: APIDataType) => string;
|
|
65
|
+
/** 自定义 options 默认值 */
|
|
66
|
+
customOptionsDefaultValue?: (data: OperationObject) => Record<string, any> | undefined;
|
|
67
|
+
/** 自定义类名 */
|
|
68
|
+
customClassName?: (tagName: string) => string;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 自定义获取type hook
|
|
72
|
+
* 返回非字符串将使用默认方法获取type
|
|
73
|
+
* @example set number to string
|
|
74
|
+
* function customType(schemaObject,namespace){
|
|
75
|
+
* if(schemaObject.type==='number' && !schemaObject.format){
|
|
76
|
+
* return 'BigDecimalString';
|
|
77
|
+
* }
|
|
78
|
+
* }
|
|
79
|
+
*/
|
|
80
|
+
customType?: (
|
|
81
|
+
schemaObject: SchemaObject | undefined,
|
|
82
|
+
namespace: string,
|
|
83
|
+
originGetType: (schemaObject: SchemaObject | undefined, namespace: string) => string,
|
|
84
|
+
) => string;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 自定义生成文件名,可返回多个,表示生成多个文件
|
|
88
|
+
* 返回为空,则使用默认的获取方法获取
|
|
89
|
+
* @example 使用operationId生成文件名
|
|
90
|
+
* function customFileNames(operationObject,apiPath){
|
|
91
|
+
* const operationId=operationObject.operationId;
|
|
92
|
+
* if (!operationId) {
|
|
93
|
+
* console.warn('[Warning] no operationId', apiPath);
|
|
94
|
+
* return;
|
|
95
|
+
* }
|
|
96
|
+
* const res = operationId.split('_');
|
|
97
|
+
* if (res.length > 1) {
|
|
98
|
+
* res.shift();
|
|
99
|
+
* if (res.length > 2) {
|
|
100
|
+
* console.warn('[Warning] operationId has more than 2 part', apiPath);
|
|
101
|
+
* }
|
|
102
|
+
* return [res.join('_')];
|
|
103
|
+
* } else {
|
|
104
|
+
* const controllerName = (res || [])[0];
|
|
105
|
+
* if (controllerName) {
|
|
106
|
+
* return [controllerName];
|
|
107
|
+
* }
|
|
108
|
+
* return;
|
|
109
|
+
* }
|
|
110
|
+
* }
|
|
111
|
+
*/
|
|
112
|
+
customFileNames?: (operationObject: OperationObject, apiPath: string, _apiMethod: string) => string[];
|
|
113
|
+
};
|
|
114
|
+
namespace?: string;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 默认为false,true时使用null代替可选
|
|
118
|
+
*/
|
|
119
|
+
nullable?: boolean;
|
|
120
|
+
|
|
121
|
+
mockFolder?: string;
|
|
122
|
+
/**
|
|
123
|
+
* 模板文件的文件路径
|
|
124
|
+
*/
|
|
125
|
+
templatesFolder?: string;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 枚举样式
|
|
129
|
+
*/
|
|
130
|
+
enumStyle?: "string-literal" | "enum";
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* response中数据字段
|
|
134
|
+
* example: ['result', 'res']
|
|
135
|
+
*/
|
|
136
|
+
dataFields?: string[];
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 模板文件、请求函数采用小驼峰命名
|
|
140
|
+
*/
|
|
141
|
+
isCamelCase?: boolean;
|
|
142
|
+
/**
|
|
143
|
+
* mock配置
|
|
144
|
+
*/
|
|
145
|
+
mockConfig?: {
|
|
146
|
+
/**
|
|
147
|
+
* msw类型mock文件格式. 直接返回对象
|
|
148
|
+
* 举例:
|
|
149
|
+
* // @ts-ignore
|
|
150
|
+
|
|
151
|
+
export default {
|
|
152
|
+
'DELETE /mydata/delete': { message: { message: 'Mydata successfully deleted' } },
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
原文件:
|
|
157
|
+
// @ts-ignore
|
|
158
|
+
import { Request, Response } from 'express';
|
|
159
|
+
|
|
160
|
+
export default {
|
|
161
|
+
'DELETE /mydata/delete': (req: Request, res: Response) => {
|
|
162
|
+
res.status(200).send({ message: { message: 'Mydata successfully deleted' } });
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
*/
|
|
166
|
+
msw?: boolean;
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const converterSwaggerToOpenApi = (swagger: any) => {
|
|
171
|
+
if (!swagger.swagger) {
|
|
172
|
+
return swagger;
|
|
173
|
+
}
|
|
174
|
+
return new Promise((resolve, reject) => {
|
|
175
|
+
converter.convertObj(swagger, {}, (err: any, options: any) => {
|
|
176
|
+
Log(["💺 将 Swagger 转化为 openAPI"]);
|
|
177
|
+
if (err) {
|
|
178
|
+
reject(err);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
resolve(options.openapi);
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export const getSchema = async (schemaPath: string, authorization?: string) => {
|
|
187
|
+
if (schemaPath.startsWith("http")) {
|
|
188
|
+
const protocol = schemaPath.startsWith("https:") ? https : http;
|
|
189
|
+
try {
|
|
190
|
+
const agent = new protocol.Agent({
|
|
191
|
+
rejectUnauthorized: false,
|
|
192
|
+
});
|
|
193
|
+
const headers: Record<string, string> = {};
|
|
194
|
+
if (authorization) {
|
|
195
|
+
headers.authorization = authorization;
|
|
196
|
+
}
|
|
197
|
+
const json = await fetch(schemaPath, { agent, headers }).then((rest: any) => rest.json());
|
|
198
|
+
return json;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
console.log("fetch openapi error:", error);
|
|
201
|
+
}
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
const raw = readFileSync(schemaPath, "utf-8");
|
|
205
|
+
return JSON.parse(raw);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const getOpenAPIConfig = async (schemaPath: string, authorization?: string) => {
|
|
209
|
+
const schema = await getSchema(schemaPath, authorization);
|
|
210
|
+
if (!schema) {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
const openAPI = await converterSwaggerToOpenApi(schema);
|
|
214
|
+
return openAPI;
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
// 从 appName 生成 service 数据
|
|
218
|
+
export const ttOpenAPI = async ({
|
|
219
|
+
authorization,
|
|
220
|
+
requestLibPath,
|
|
221
|
+
schemaPath,
|
|
222
|
+
mockFolder,
|
|
223
|
+
nullable = false,
|
|
224
|
+
requestOptionsType = "{[key: string]: any}",
|
|
225
|
+
...rest
|
|
226
|
+
}: GenerateServiceProps) => {
|
|
227
|
+
const openAPI = await getOpenAPIConfig(schemaPath!, authorization);
|
|
228
|
+
const requestImportStatement = getImportStatement(requestLibPath!);
|
|
229
|
+
const serviceGenerator = new ServiceGenerator(
|
|
230
|
+
{
|
|
231
|
+
namespace: "API",
|
|
232
|
+
requestOptionsType,
|
|
233
|
+
requestImportStatement,
|
|
234
|
+
enumStyle: "string-literal",
|
|
235
|
+
nullable,
|
|
236
|
+
isCamelCase: true,
|
|
237
|
+
mockConfig: {},
|
|
238
|
+
...rest,
|
|
239
|
+
},
|
|
240
|
+
openAPI,
|
|
241
|
+
);
|
|
242
|
+
await serviceGenerator.genFile();
|
|
243
|
+
|
|
244
|
+
if (mockFolder) {
|
|
245
|
+
await mockGenerator({
|
|
246
|
+
openAPI,
|
|
247
|
+
mockFolder: mockFolder || "./mocks/",
|
|
248
|
+
mockConfig: rest.mockConfig || {},
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
};
|
package/src/log.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import Mock from "mockjs";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import { prettierFile, writeFile } from "./util";
|
|
4
|
+
import { dirname, join } from "path";
|
|
5
|
+
import OpenAPIParserMock from "./openAPIParserMock/index";
|
|
6
|
+
import Log from "./log";
|
|
7
|
+
import pinyin from "tiny-pinyin";
|
|
8
|
+
import { GenerateServiceProps } from "./index";
|
|
9
|
+
Mock.Random.extend({
|
|
10
|
+
country() {
|
|
11
|
+
const data = [
|
|
12
|
+
"阿根廷",
|
|
13
|
+
"澳大利亚",
|
|
14
|
+
"巴西",
|
|
15
|
+
"加拿大",
|
|
16
|
+
"中国",
|
|
17
|
+
"法国",
|
|
18
|
+
"德国",
|
|
19
|
+
"印度",
|
|
20
|
+
"印度尼西亚",
|
|
21
|
+
"意大利",
|
|
22
|
+
"日本",
|
|
23
|
+
"韩国",
|
|
24
|
+
"墨西哥",
|
|
25
|
+
"俄罗斯",
|
|
26
|
+
"沙特阿拉伯",
|
|
27
|
+
"南非",
|
|
28
|
+
"土耳其",
|
|
29
|
+
"英国",
|
|
30
|
+
"美国",
|
|
31
|
+
];
|
|
32
|
+
const id = (Math.random() * data.length).toFixed();
|
|
33
|
+
return data[id];
|
|
34
|
+
},
|
|
35
|
+
phone() {
|
|
36
|
+
const phonepreFix = ["111", "112", "114"]; // 自己写前缀哈
|
|
37
|
+
return this.pick(phonepreFix) + Mock.mock(/\d{8}/); // Number()
|
|
38
|
+
},
|
|
39
|
+
status() {
|
|
40
|
+
const status = ["success", "error", "default", "processing", "warning"];
|
|
41
|
+
return status[(Math.random() * 4).toFixed(0)];
|
|
42
|
+
},
|
|
43
|
+
authority() {
|
|
44
|
+
const status = ["admin", "user", "guest"];
|
|
45
|
+
return status[(Math.random() * status.length).toFixed(0)];
|
|
46
|
+
},
|
|
47
|
+
avatar() {
|
|
48
|
+
const avatar = [
|
|
49
|
+
"https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg",
|
|
50
|
+
"https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png",
|
|
51
|
+
"https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png",
|
|
52
|
+
"https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png",
|
|
53
|
+
"https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png",
|
|
54
|
+
"https://avatars0.githubusercontent.com/u/507615?s=40&v=4",
|
|
55
|
+
"https://avatars1.githubusercontent.com/u/8186664?s=40&v=4",
|
|
56
|
+
];
|
|
57
|
+
const id = (Math.random() * avatar.length).toFixed();
|
|
58
|
+
return avatar[id];
|
|
59
|
+
},
|
|
60
|
+
group() {
|
|
61
|
+
const data = ["体验技术部", "创新科技组", "前端 6 组", "区块链平台部", "服务技术部"];
|
|
62
|
+
const id = (Math.random() * data.length).toFixed();
|
|
63
|
+
return data[id];
|
|
64
|
+
},
|
|
65
|
+
label() {
|
|
66
|
+
const label = [
|
|
67
|
+
"很有想法的",
|
|
68
|
+
"小清新",
|
|
69
|
+
"傻白甜",
|
|
70
|
+
"阳光少年",
|
|
71
|
+
"大咖",
|
|
72
|
+
"健身达人",
|
|
73
|
+
"程序员",
|
|
74
|
+
"算法工程师",
|
|
75
|
+
"川妹子",
|
|
76
|
+
"名望程序员",
|
|
77
|
+
"大长腿",
|
|
78
|
+
"海纳百川",
|
|
79
|
+
"专注设计",
|
|
80
|
+
"爱好广泛",
|
|
81
|
+
"IT 互联网",
|
|
82
|
+
];
|
|
83
|
+
const id = (Math.random() * label.length).toFixed();
|
|
84
|
+
return label[id];
|
|
85
|
+
},
|
|
86
|
+
href() {
|
|
87
|
+
const href = [
|
|
88
|
+
"https://preview.pro.ant.design/dashboard/analysis",
|
|
89
|
+
"https://ant.design",
|
|
90
|
+
"https://procomponents.ant.design/",
|
|
91
|
+
"https://umijs.org/",
|
|
92
|
+
"https://github.com/umijs/dumi",
|
|
93
|
+
];
|
|
94
|
+
const id = (Math.random() * href.length).toFixed();
|
|
95
|
+
return href[id];
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const genMockData = (example: string) => {
|
|
100
|
+
if (!example) {
|
|
101
|
+
return {};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (typeof example === "string") {
|
|
105
|
+
return Mock.mock(example);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (Array.isArray(example)) {
|
|
109
|
+
return Mock.mock(example);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return Object.keys(example)
|
|
113
|
+
.map(name => {
|
|
114
|
+
return {
|
|
115
|
+
[name]: Mock.mock(example[name]),
|
|
116
|
+
};
|
|
117
|
+
})
|
|
118
|
+
.reduce((pre, next) => {
|
|
119
|
+
return {
|
|
120
|
+
...pre,
|
|
121
|
+
...next,
|
|
122
|
+
};
|
|
123
|
+
}, {});
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const genByTemp = ({
|
|
127
|
+
method,
|
|
128
|
+
path,
|
|
129
|
+
parameters,
|
|
130
|
+
status,
|
|
131
|
+
data,
|
|
132
|
+
mockConfig,
|
|
133
|
+
}: {
|
|
134
|
+
method: string;
|
|
135
|
+
path: string;
|
|
136
|
+
parameters: {
|
|
137
|
+
name: string;
|
|
138
|
+
in: string;
|
|
139
|
+
description: string;
|
|
140
|
+
required: boolean;
|
|
141
|
+
schema: { type: string };
|
|
142
|
+
example: string;
|
|
143
|
+
}[];
|
|
144
|
+
status: string;
|
|
145
|
+
data: string;
|
|
146
|
+
mockConfig: GenerateServiceProps["mockConfig"];
|
|
147
|
+
}) => {
|
|
148
|
+
if (!["get", "put", "post", "delete", "patch"].includes(method.toLocaleLowerCase())) {
|
|
149
|
+
return "";
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let securityPath = path;
|
|
153
|
+
parameters?.forEach(item => {
|
|
154
|
+
if (item.in === "path") {
|
|
155
|
+
securityPath = securityPath.replace(`{${item.name}}`, `:${item.name}`);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
if (mockConfig.msw) {
|
|
160
|
+
return `'${method.toUpperCase()} ${securityPath}': ${data}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return `'${method.toUpperCase()} ${securityPath}': (req: Request, res: Response) => {
|
|
164
|
+
res.status(${status}).send(${data});
|
|
165
|
+
}`;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const genMockFiles = (mockFunction: string[], mockConfig: GenerateServiceProps["mockConfig"]) => {
|
|
169
|
+
return prettierFile(`
|
|
170
|
+
// @ts-ignore
|
|
171
|
+
${mockConfig.msw ? "" : "import { Request, Response } from 'express'"}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
export default {
|
|
175
|
+
${mockFunction.join("\n,")}
|
|
176
|
+
}`)[0];
|
|
177
|
+
};
|
|
178
|
+
export type genMockDataServerConfig = {
|
|
179
|
+
openAPI: any;
|
|
180
|
+
mockFolder: string;
|
|
181
|
+
mockConfig: GenerateServiceProps["mockConfig"];
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const mockGenerator = async ({ openAPI, mockFolder, mockConfig }: genMockDataServerConfig) => {
|
|
185
|
+
const openAPParse = new OpenAPIParserMock(openAPI);
|
|
186
|
+
const docs = openAPParse.parser();
|
|
187
|
+
const pathList = Object.keys(docs.paths);
|
|
188
|
+
const { paths } = docs;
|
|
189
|
+
const mockActionsObj = {};
|
|
190
|
+
pathList.forEach(path => {
|
|
191
|
+
const pathConfig = paths[path];
|
|
192
|
+
Object.keys(pathConfig).forEach(method => {
|
|
193
|
+
const methodConfig = pathConfig[method];
|
|
194
|
+
if (methodConfig) {
|
|
195
|
+
let conte = (
|
|
196
|
+
methodConfig.operationId ||
|
|
197
|
+
methodConfig?.tags?.join("/") ||
|
|
198
|
+
path.replace("/", "").split("/")[1]
|
|
199
|
+
)?.replace(/[^\w^\s^\u4e00-\u9fa5]/gi, "");
|
|
200
|
+
if (/[\u3220-\uFA29]/.test(conte)) {
|
|
201
|
+
conte = pinyin.convertToPinyin(conte, "", true);
|
|
202
|
+
}
|
|
203
|
+
if (!conte) {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const data = genMockData(methodConfig.responses?.["200"]?.example);
|
|
207
|
+
if (!mockActionsObj[conte]) {
|
|
208
|
+
mockActionsObj[conte] = [];
|
|
209
|
+
}
|
|
210
|
+
const tempFile = genByTemp({
|
|
211
|
+
method,
|
|
212
|
+
path,
|
|
213
|
+
parameters: methodConfig.parameters,
|
|
214
|
+
status: "200",
|
|
215
|
+
data: JSON.stringify(data),
|
|
216
|
+
mockConfig,
|
|
217
|
+
});
|
|
218
|
+
if (tempFile) {
|
|
219
|
+
mockActionsObj[conte].push(tempFile);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
Object.keys(mockActionsObj).forEach(file => {
|
|
225
|
+
if (!file || file === "undefined") {
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (file.includes("/")) {
|
|
229
|
+
const dirName = dirname(join(mockFolder, `${file}.ts`));
|
|
230
|
+
if (!fs.existsSync(dirName)) {
|
|
231
|
+
fs.mkdirSync(dirName);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
writeFile(mockFolder, `${file}.ts`, genMockFiles(mockActionsObj[file], mockConfig));
|
|
235
|
+
});
|
|
236
|
+
Log("✅ 生成 mock 文件成功");
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
export { mockGenerator };
|