@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.
@@ -0,0 +1,6 @@
1
+ declare module 'node-fetch';
2
+ declare module 'swagger2openapi';
3
+ declare module 'reserved-words';
4
+ declare module 'tiny-pinyin';
5
+ declare module 'number-to-words';
6
+ declare module 'memoizee';
package/src/util.ts ADDED
@@ -0,0 +1,203 @@
1
+ /* eslint-disable guard-for-in */
2
+ /* eslint-disable no-restricted-syntax */
3
+ /* eslint-disable no-lonely-if */
4
+ /* eslint-disable no-param-reassign */
5
+ import path from "path";
6
+ import fs from "fs";
7
+ import { camelCase, upperFirst } from "lodash-es";
8
+
9
+ export const getAbsolutePath = (filePath: string) => {
10
+ if (filePath && !path.isAbsolute(filePath)) {
11
+ return path.join(process.cwd(), filePath);
12
+ }
13
+ return filePath;
14
+ };
15
+
16
+ export const mkdir = (dir: string) => {
17
+ if (!fs.existsSync(dir)) {
18
+ mkdir(path.dirname(dir));
19
+ fs.mkdirSync(dir);
20
+ }
21
+ };
22
+
23
+ export const prettierFile = async (content: string): Promise<[string, boolean]> => {
24
+ let result = content;
25
+ let hasError = false;
26
+ try {
27
+ const prettier = await import("prettier");
28
+ const prettierOptions = await prettier.resolveConfig(process.cwd());
29
+ result = await prettier.format(content, {
30
+ parser: "typescript",
31
+ ...prettierOptions,
32
+ });
33
+ } catch (error: any) {
34
+ console.error("Prettier error:", error);
35
+ hasError = true;
36
+ }
37
+ return [result, hasError];
38
+ };
39
+
40
+ export const writeFile = async (folderPath: string, fileName: string, content: string) => {
41
+ const filePath = path.join(folderPath, fileName);
42
+ mkdir(path.dirname(filePath));
43
+ const [prettierContent, hasError] = await prettierFile(content);
44
+ fs.writeFileSync(filePath, prettierContent, {
45
+ encoding: "utf8",
46
+ });
47
+ return hasError;
48
+ };
49
+
50
+ export const getTagName = (name: string) => {
51
+ const result = name.split(".");
52
+ // 数据源中的 tag 等同于全量的 op API 名,确定为 4-5 段,如上格式
53
+ // 取中间的 1-2 字段作为 tag,作为 serviceController 创建目录的依据
54
+ if (result.length === 4) {
55
+ return result[2];
56
+ }
57
+ if (result.length === 5) {
58
+ return result[2] + upperFirst(result[3]);
59
+ }
60
+ return name;
61
+ };
62
+
63
+ /**
64
+ * 根据当前的数据源类型,对请求回来的 apiInfo 进行格式化
65
+ * 如果是 op 数据源,对 tags 以及 path 中的 tags 进行处理
66
+ * - before: 前缀(产品集.产品码) + 操作对象(必填)+ 子操作对象(可选)+ 动作(必填)
67
+ * - after: 操作对象(必填)+ 子操作对象(可选) ==> 驼峰
68
+ */
69
+ export const formatApiInfo = (apiInfo: Record<string, any>): any => {
70
+ if (
71
+ !(
72
+ apiInfo &&
73
+ apiInfo.schema.info &&
74
+ apiInfo.schema.info.extensions &&
75
+ apiInfo.schema.info.extensions["x-antTech-description"]
76
+ )
77
+ ) {
78
+ // 非 op 数据源,直接返回
79
+ return apiInfo;
80
+ }
81
+
82
+ apiInfo.schema.tags = apiInfo.schema.tags.map((item: Record<string, string>) => {
83
+ return {
84
+ ...item,
85
+ name: getTagName(item.name),
86
+ };
87
+ });
88
+
89
+ for (const child_path in apiInfo.schema.paths) {
90
+ apiInfo.schema.paths[child_path].post.tags = apiInfo.schema.paths[child_path].post.tags.map((tag: string) =>
91
+ getTagName(tag),
92
+ );
93
+ }
94
+
95
+ return apiInfo;
96
+ };
97
+
98
+ type serviceParam = {
99
+ title: string;
100
+ type: string;
101
+ description: string;
102
+ default: string;
103
+ [key: string]: any;
104
+ };
105
+
106
+ type serviceParams = Record<string, serviceParam>;
107
+ /**
108
+ * 一方化场景下,由于 onex 会对请求的响应做处理
109
+ * 1. 将 Response & Request 中的参数字段会变更为小驼峰写法
110
+ * onex 相关代码 : http://gitlab.alipay-inc.com/one-console/sdk/blob/master/src/request.ts#L110
111
+ * 2. 另外要注意:
112
+ * op 返回的数据,请求参数的类型格式 需要做额外的处理
113
+ * - (name) key.n, (type) string ==> key: string []
114
+ * - (name) key.m, (type) string ===> key: string []
115
+ * - (name) key.key1 , (type) string ==> key: {key1:string}
116
+ * - (name) key.n.key1 ,(type) string => key:{ key1 :string}[]
117
+ * - (name) key.n.key1.m,(type) string ==> key:{key1: string[]}[]
118
+ */
119
+ export function formatParamsForYFH(params: serviceParams, paramsObject: serviceParams = {}): serviceParams {
120
+ Object.keys(params).forEach(name => {
121
+ const prop = params[name];
122
+ let key = name;
123
+ const nameList = name.split(".");
124
+ const nameListLength = nameList.length;
125
+
126
+ if (nameListLength === 1) {
127
+ // 正常的 key
128
+ paramsObject[key] = { ...prop };
129
+ } else if (nameListLength === 2 && nameList[1] !== "n" && nameList[1] !== "m") {
130
+ const [childKey] = nameList;
131
+ // key.child_key
132
+ const key_child_key = camelCase(nameList[1]);
133
+ paramsObject[childKey] = combineParams(childKey, key_child_key, prop, paramsObject);
134
+ } else {
135
+ // key.n.child_key
136
+ if (nameList[nameListLength - 2] === "n" || nameList[nameListLength - 2] === "m") {
137
+ const child_key = camelCase(nameList.pop());
138
+ nameList.pop();
139
+ key = nameList.join(".");
140
+ paramsObject[key] = combineParams(key, child_key, prop, paramsObject, ".n.key");
141
+ } else {
142
+ const child_key = camelCase(nameList.pop());
143
+ key = nameList.join(".");
144
+
145
+ // .key.n
146
+ if (child_key === "n" || child_key === "m") {
147
+ // .n.key.m
148
+ if (nameList[nameList.length - 2] === "n" || nameList[nameList.length - 2] === "m") {
149
+ const child_child_key = camelCase(nameList.pop());
150
+ nameList.pop();
151
+ key = nameList.join(".");
152
+ paramsObject[key] = combineParams(key, child_child_key, prop, paramsObject, ".n.key.m");
153
+ } else {
154
+ prop.type = `${prop.type}[]`;
155
+ paramsObject[key] = { ...prop };
156
+ }
157
+ } else {
158
+ paramsObject[key] = combineParams(key, child_key, prop, paramsObject);
159
+ }
160
+ }
161
+ }
162
+
163
+ paramsObject[key].name = camelCase(key);
164
+ });
165
+
166
+ const hasInvoke = Object.keys(paramsObject).filter(param => param.includes(".")).length > 0;
167
+
168
+ if (hasInvoke) {
169
+ // 递归
170
+ return formatParamsForYFH(paramsObject);
171
+ }
172
+ return paramsObject;
173
+ }
174
+
175
+ function combineParams(
176
+ key: string,
177
+ child_key: string,
178
+ prop: serviceParam,
179
+ paramsObject: serviceParams,
180
+ type?: string,
181
+ ): serviceParam {
182
+ const typeSuffix = type === ".n.key.m" ? "[]" : "";
183
+ const keySuffix = type === ".n.key" || type === ".n.key.m" ? "[]" : "";
184
+ if (paramsObject[key]) {
185
+ const child_type = `{${child_key}:${prop.type}${typeSuffix}, ${paramsObject[key].type.slice(1)}`;
186
+ paramsObject[key] = {
187
+ ...paramsObject[key],
188
+ type: child_type,
189
+ };
190
+ } else {
191
+ paramsObject[key] = {
192
+ ...prop,
193
+ type: `{${child_key}:${prop.type}
194
+ }${keySuffix}`,
195
+ };
196
+ }
197
+
198
+ return paramsObject[key];
199
+ }
200
+
201
+ export const stripDot = (str: string) => {
202
+ return str.replace(/[-_ .](\w)/g, (_all, letter) => letter.toUpperCase());
203
+ };
@@ -0,0 +1,54 @@
1
+ declare namespace {{ namespace }} {
2
+ {% for type in list -%}
3
+ {%- if type.props.length %}
4
+ {%- if type.isEnum %}
5
+ enum {{ type.typeName | safe }}
6
+ {%- else %}
7
+ {{ declareType }} {{ type.typeName | safe }} {{ equalSymbol }}
8
+ {%- endif %}
9
+ {%- for prop in type.props %}
10
+ {%- if prop.length > 1 %}
11
+ {
12
+ {%- endif %}
13
+ {%- if prop.length == 1 %}
14
+ {%- if not prop[0].$ref or prop[0].name %}
15
+ {
16
+ {%- endif %}
17
+ {%- endif %}
18
+ {%- for p in prop %}
19
+ {%- if p.desc %}
20
+ /** {{ p.desc }} */
21
+ {%- endif %}
22
+ {%- if p["$ref"] and not p.name %}
23
+ // {{ p.$ref }}
24
+ {{ p.type | safe }}
25
+ {%- else %}
26
+ {%- if nullable %}
27
+ '{{ p.name }}': {{ p.type | safe }}{{'' if p.required else '| null'}};
28
+ {%- else %}
29
+ '{{ p.name }}'{{ '' if p.required else '?' }}: {{ p.type | safe }};
30
+ {%- endif %}
31
+ {%- endif %}
32
+ {%- endfor %}
33
+ {%- if prop.length > 1 %}
34
+ }
35
+ {%- endif %}
36
+ {%- if prop.length == 1 %}
37
+ {%- if not prop[0].$ref or prop[0].name %}
38
+ }
39
+ {%- endif %}
40
+ {%- endif %}
41
+ {%- if prop.length == 0 %}
42
+ {}
43
+ {%- endif %}
44
+ {{ '' if loop.last === true else ' & ' }}
45
+ {%- endfor %}
46
+ {%- else %}
47
+ {%- if type.isEnum %}
48
+ enum {{ type.typeName | safe }} {{ type.type }};
49
+ {%- else %}
50
+ type {{ type.typeName | safe }} = {{ type.type }};
51
+ {%- endif %}
52
+ {%- endif %}
53
+ {% endfor %}
54
+ }
@@ -0,0 +1,38 @@
1
+ // @ts-ignore
2
+ /* eslint-disable */
3
+ {{ requestImportStatement }}
4
+
5
+ {% for api in list -%}
6
+ /** {{ api.desc if api.desc else '此处后端没有提供注释' }} {{api.method | upper}} {{ api.pathInComment | safe }} */
7
+ export async function {{ api.functionName }}(
8
+ {%- if api.body -%}
9
+ params
10
+ {%- if genType === "ts" -%}
11
+ : {% if api.body.propertiesList %}{
12
+ {%- for prop in api.body.propertiesList %}
13
+ {% if prop.schema.description -%}
14
+ /** {{ prop.schema.description }} */
15
+ {% endif -%}
16
+ {{ prop.key }}{{ "?" if not prop.schema.required }}: {{ prop.schema.type }},
17
+ {%- endfor %}
18
+ }
19
+ {%- else -%}
20
+ {{ api.body.type }}
21
+ {%- endif -%}
22
+ {%- endif -%}
23
+ {%- elif api.params and api.hasParams -%}
24
+ params
25
+ {%- if genType === "ts" -%}
26
+ : {{namespace}}.{{api.typeName}}
27
+ {%- endif -%}
28
+ {%- endif -%}
29
+ ) {
30
+ return request.{{ "del" if api.method | lower == "delete" else api.method | lower }}{{ ("<" + api.response.type + ">") | safe if genType === "ts" }}({
31
+ url: '{{ api.path }}',
32
+ {%- if api.body or (api.params and api.hasParams) %}
33
+ {{ "data" if api.method | lower == "delete" else "params" }}: params,
34
+ {%- endif %}
35
+ });
36
+ }
37
+
38
+ {% endfor -%}
@@ -0,0 +1,14 @@
1
+ // @ts-ignore
2
+ /* eslint-disable */
3
+ // API 更新时间:{{ apiResourceModifyTime }}
4
+ // API 唯一标识:{{ apiResourceId }}
5
+ {% for api in list -%}
6
+ import * as {{ api.controllerName }} from './{{ api.fileName }}'
7
+ {% endfor -%}
8
+
9
+
10
+ export default {
11
+ {% for api in list -%}
12
+ {{ api.controllerName }},
13
+ {% endfor -%}
14
+ }
package/tsconfig.json CHANGED
@@ -9,5 +9,6 @@
9
9
  "declaration": false,
10
10
  "declarationMap": false
11
11
  },
12
- "include": ["src/**/*"]
12
+ "include": ["src/**/*"],
13
+ "exclude": ["node_modules", "dist"]
13
14
  }
package/openapi.config.ts DELETED
@@ -1,16 +0,0 @@
1
- import type { OpenAPIConfig } from "./src/types";
2
-
3
- const config: OpenAPIConfig = {
4
- outputDir: "./generated",
5
-
6
- /** 网关地址,自动发现所有微服务的 OpenAPI 文档 */
7
- gateway: "http://192.168.129.178:11000",
8
-
9
- /** 请求函数的导入路径,生成的接口会 import request from 此路径 */
10
- requestImportPath: "@dazhicheng/utils",
11
-
12
- /** 请求函数名称 */
13
- requestFnName: "request",
14
- };
15
-
16
- export default config;
package/src/discovery.ts DELETED
@@ -1,44 +0,0 @@
1
- import type { ServiceConfig } from "./types";
2
-
3
- interface SwaggerConfigUrl {
4
- name: string;
5
- url: string;
6
- contextPath?: string;
7
- }
8
-
9
- interface SwaggerConfig {
10
- urls: SwaggerConfigUrl[];
11
- }
12
-
13
- /**
14
- * 从 Knife4j / SpringDoc 网关自动发现所有微服务的 OpenAPI 文档地址
15
- */
16
- export async function discoverServices(baseUrl: string): Promise<ServiceConfig[]> {
17
- const configUrl = `${baseUrl}/v3/api-docs/swagger-config`;
18
-
19
- const response = await fetch(configUrl, {
20
- headers: { Accept: "application/json" },
21
- });
22
-
23
- if (!response.ok) {
24
- throw new Error(`获取 swagger-config 失败: ${configUrl} (HTTP ${response.status})`);
25
- }
26
-
27
- const config = (await response.json()) as SwaggerConfig;
28
-
29
- if (!config.urls || config.urls.length === 0) {
30
- throw new Error("swagger-config 中未发现任何服务");
31
- }
32
-
33
- return config.urls.map(item => {
34
- const pathSegments = item.url.split("/").filter(Boolean);
35
- const serviceName = pathSegments[0] || item.name;
36
-
37
- return {
38
- name: serviceName,
39
- url: `${baseUrl}${item.url}`,
40
- description: item.name,
41
- pathPrefix: item.contextPath || `/${serviceName}`,
42
- };
43
- });
44
- }
package/src/fetcher.ts DELETED
@@ -1,19 +0,0 @@
1
- import type { SwaggerDoc } from "./types";
2
-
3
- export async function fetchSwaggerDoc(url: string): Promise<SwaggerDoc> {
4
- const response = await fetch(url, {
5
- headers: { Accept: "application/json" },
6
- });
7
-
8
- if (!response.ok) {
9
- throw new Error(`获取 Swagger 文档失败: ${url} (HTTP ${response.status})`);
10
- }
11
-
12
- const doc = (await response.json()) as SwaggerDoc;
13
-
14
- if (!doc.paths) {
15
- throw new Error(`无效的 Swagger 文档 (缺少 paths): ${url}`);
16
- }
17
-
18
- return doc;
19
- }
package/src/formatter.ts DELETED
@@ -1,16 +0,0 @@
1
- import prettier from "prettier";
2
-
3
- export async function formatTypeScript(code: string): Promise<string> {
4
- try {
5
- return await prettier.format(code, {
6
- parser: "typescript",
7
- semi: true,
8
- singleQuote: true,
9
- trailingComma: "all",
10
- printWidth: 100,
11
- tabWidth: 2,
12
- });
13
- } catch {
14
- return code;
15
- }
16
- }
package/src/generator.ts DELETED
@@ -1,187 +0,0 @@
1
- import type { ParseResult, ParsedAPI, ParsedInterface, ParsedProperty } from "./parser";
2
-
3
- export interface GeneratorOptions {
4
- requestImportPath: string;
5
- requestFnName: string;
6
- serviceName: string;
7
- serviceDescription?: string;
8
- }
9
-
10
- export function generateServiceFile(result: ParseResult, options: GeneratorOptions): string {
11
- const lines: string[] = [];
12
- const { requestImportPath, requestFnName } = options;
13
-
14
- lines.push(`// 此文件由 @dazhicheng/openapi 自动生成,请勿手动修改`);
15
- lines.push(`// 服务: ${options.serviceDescription || options.serviceName}`);
16
- lines.push(`// 生成时间: ${new Date().toISOString()}`);
17
- lines.push("");
18
- lines.push(`import ${requestFnName} from '${requestImportPath}';`);
19
- lines.push("");
20
-
21
- lines.push("// ======================== 类型定义 ========================");
22
- lines.push("");
23
-
24
- for (const iface of result.interfaces) {
25
- lines.push(generateInterface(iface));
26
- lines.push("");
27
- }
28
-
29
- const apisByTag = groupApisByTag(result.apis, result.tags);
30
-
31
- lines.push("// ======================== 接口方法 ========================");
32
- lines.push("");
33
-
34
- for (const [tagName, tagApis] of Object.entries(apisByTag)) {
35
- const tagInfo = result.tags.find(t => t.name === tagName);
36
- if (tagInfo?.description) {
37
- lines.push(`// ---------- ${tagInfo.description} ----------`);
38
- } else if (tagName !== "__ungrouped__") {
39
- lines.push(`// ---------- ${tagName} ----------`);
40
- }
41
- lines.push("");
42
-
43
- for (const api of tagApis) {
44
- lines.push(generateApiFunction(api, requestFnName));
45
- lines.push("");
46
- }
47
- }
48
-
49
- return lines.join("\n");
50
- }
51
-
52
- function generateInterface(iface: ParsedInterface): string {
53
- const lines: string[] = [];
54
-
55
- if (iface.description) {
56
- lines.push(`/** ${iface.description} */`);
57
- }
58
- lines.push(`export interface ${iface.name} {`);
59
-
60
- for (const prop of iface.properties) {
61
- if (prop.description) {
62
- lines.push(` /** ${prop.description} */`);
63
- }
64
- const optional = prop.required ? "" : "?";
65
- const safeName = isValidIdentifier(prop.name) ? prop.name : `'${prop.name}'`;
66
- lines.push(` ${safeName}${optional}: ${prop.type};`);
67
- }
68
-
69
- lines.push("}");
70
- return lines.join("\n");
71
- }
72
-
73
- function generateApiFunction(api: ParsedAPI, requestFnName: string): string {
74
- const lines: string[] = [];
75
-
76
- const jsdocLines: string[] = [];
77
- if (api.summary || api.description) {
78
- jsdocLines.push(api.summary || api.description || "");
79
- }
80
- if (api.deprecated) {
81
- jsdocLines.push("@deprecated");
82
- }
83
- if (api.description && api.summary && api.description !== api.summary) {
84
- jsdocLines.push(`@description ${api.description}`);
85
- }
86
-
87
- if (jsdocLines.length > 0) {
88
- lines.push("/**");
89
- for (const line of jsdocLines) {
90
- lines.push(` * ${line}`);
91
- }
92
- lines.push(" */");
93
- }
94
-
95
- const params = buildFunctionParams(api);
96
- const genericType = api.responseType !== "void" ? `<${api.responseType}>` : "";
97
- const fnSignature = `export function ${api.name}(${params})`;
98
-
99
- const urlExpr = buildUrlExpression(api.path, api.pathParams);
100
- const requestConfig = buildRequestConfig(api);
101
-
102
- lines.push(`${fnSignature} {`);
103
- lines.push(` return ${requestFnName}${genericType}({`);
104
- lines.push(` url: ${urlExpr},`);
105
- lines.push(` method: '${api.method}',`);
106
- if (requestConfig) {
107
- lines.push(requestConfig);
108
- }
109
- lines.push(" });");
110
- lines.push("}");
111
-
112
- return lines.join("\n");
113
- }
114
-
115
- function buildFunctionParams(api: ParsedAPI): string {
116
- const params: string[] = [];
117
-
118
- for (const p of api.pathParams) {
119
- params.push(`${p.name}: ${p.type}`);
120
- }
121
-
122
- if (api.queryParams.length > 0) {
123
- const paramTypeParts = api.queryParams.map(p => {
124
- const optional = p.required ? "" : "?";
125
- return `${p.name}${optional}: ${p.type}`;
126
- });
127
- const allOptional = api.queryParams.every(p => !p.required);
128
- params.push(`params${allOptional ? "?" : ""}: { ${paramTypeParts.join("; ")} }`);
129
- }
130
-
131
- if (api.bodyType) {
132
- const bodyOptional = api.bodyRequired === false ? "?" : "";
133
- params.push(`data${bodyOptional}: ${api.bodyType}`);
134
- }
135
-
136
- return params.join(", ");
137
- }
138
-
139
- function buildUrlExpression(path: string, pathParams: ParsedProperty[]): string {
140
- if (pathParams.length === 0) {
141
- return `'${path}'`;
142
- }
143
-
144
- const templatePath = path.replace(/\{(\w+)\}/g, (_match, name) => {
145
- return `\${${name}}`;
146
- });
147
- return "`" + templatePath + "`";
148
- }
149
-
150
- function buildRequestConfig(api: ParsedAPI): string | undefined {
151
- const parts: string[] = [];
152
-
153
- if (api.queryParams.length > 0) {
154
- parts.push(" params,");
155
- }
156
-
157
- if (api.bodyType) {
158
- parts.push(" data,");
159
- }
160
-
161
- if (api.hasFormData) {
162
- parts.push(" headers: { 'Content-Type': 'multipart/form-data' },");
163
- }
164
-
165
- return parts.length > 0 ? parts.join("\n") : undefined;
166
- }
167
-
168
- function groupApisByTag(
169
- apis: ParsedAPI[],
170
- _tags: Array<{ name: string; description?: string }>,
171
- ): Record<string, ParsedAPI[]> {
172
- const grouped: Record<string, ParsedAPI[]> = {};
173
-
174
- for (const api of apis) {
175
- const tag = api.tag || "__ungrouped__";
176
- if (!grouped[tag]) {
177
- grouped[tag] = [];
178
- }
179
- grouped[tag].push(api);
180
- }
181
-
182
- return grouped;
183
- }
184
-
185
- function isValidIdentifier(name: string): boolean {
186
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
187
- }