@dazhicheng/openapi 1.1.4 → 1.1.6

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/src/index.ts CHANGED
@@ -1,279 +1,274 @@
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
- import fs from "fs";
12
-
13
- const getImportStatement = (requestLibPath: string) => {
14
- if (requestLibPath && requestLibPath.startsWith("import")) {
15
- return requestLibPath;
16
- }
17
- if (requestLibPath) {
18
- return `import request from '${requestLibPath}'`;
19
- }
20
- return `import { request } from "umi"`;
21
- };
22
-
23
- export type GenerateServiceProps = {
24
- requestLibPath?: string;
25
- requestOptionsType?: string;
26
- requestImportStatement?: string;
27
- // interface 类型声明方式, 满足某些团队的开发规范
28
- declareType?: "type" | "interface";
29
- /**
30
- * api 的前缀
31
- */
32
- apiPrefix?:
33
- | string
34
- | ((params: {
35
- path: string;
36
- method: string;
37
- namespace: string;
38
- functionName: string;
39
- autoExclude?: boolean;
40
- }) => string);
41
- /**
42
- * 生成的文件夹的路径
43
- */
44
- serversPath?: string;
45
- /**
46
- * Swagger 2.0 或 OpenAPI 3.0 的地址
47
- */
48
- schemaPath?: string;
49
- /**
50
- * 项目名称
51
- */
52
- projectName?: string;
53
- /**
54
- * 文档登录凭证
55
- */
56
- authorization?: string;
57
-
58
- hook?: {
59
- /** change open api data after constructor */
60
- afterOpenApiDataInited?: (openAPIData: OpenAPIObject) => OpenAPIObject;
61
-
62
- /** 自定义函数名称 */
63
- customFunctionName?: (data: APIDataType) => string;
64
- /** 自定义类型名称 */
65
- customTypeName?: (data: APIDataType) => string;
66
- /** 自定义 options 默认值 */
67
- customOptionsDefaultValue?: (data: OperationObject) => Record<string, any> | undefined;
68
- /** 自定义类名 */
69
- customClassName?: (tagName: string) => string;
70
-
71
- /**
72
- * 自定义获取type hook
73
- * 返回非字符串将使用默认方法获取type
74
- * @example set number to string
75
- * function customType(schemaObject,namespace){
76
- * if(schemaObject.type==='number' && !schemaObject.format){
77
- * return 'BigDecimalString';
78
- * }
79
- * }
80
- */
81
- customType?: (
82
- schemaObject: SchemaObject | undefined,
83
- namespace: string,
84
- originGetType: (schemaObject: SchemaObject | undefined, namespace: string) => string,
85
- ) => string;
86
-
87
- /**
88
- * 自定义生成文件名,可返回多个,表示生成多个文件
89
- * 返回为空,则使用默认的获取方法获取
90
- * @example 使用operationId生成文件名
91
- * function customFileNames(operationObject,apiPath){
92
- * const operationId=operationObject.operationId;
93
- * if (!operationId) {
94
- * console.warn('[Warning] no operationId', apiPath);
95
- * return;
96
- * }
97
- * const res = operationId.split('_');
98
- * if (res.length > 1) {
99
- * res.shift();
100
- * if (res.length > 2) {
101
- * console.warn('[Warning] operationId has more than 2 part', apiPath);
102
- * }
103
- * return [res.join('_')];
104
- * } else {
105
- * const controllerName = (res || [])[0];
106
- * if (controllerName) {
107
- * return [controllerName];
108
- * }
109
- * return;
110
- * }
111
- * }
112
- */
113
- customFileNames?: (operationObject: OperationObject, apiPath: string, _apiMethod: string) => string[];
114
- };
115
- namespace?: string;
116
-
117
- /**
118
- * 默认为false,true时使用null代替可选
119
- */
120
- nullable?: boolean;
121
-
122
- mockFolder?: string;
123
- /**
124
- * 模板文件的文件路径
125
- */
126
- templatesFolder?: string;
127
-
128
- /**
129
- * 枚举样式
130
- */
131
- enumStyle?: "string-literal" | "enum";
132
-
133
- /**
134
- * response中数据字段
135
- * example: ['result', 'res']
136
- */
137
- dataFields?: string[];
138
-
139
- /**
140
- * 模板文件、请求函数采用小驼峰命名
141
- */
142
- isCamelCase?: boolean;
143
- /**
144
- * 指定生成的接口路径列表
145
- * 传入则只生成这些接口,不传则全量生成
146
- * @example specifiedPaths: ["/user/list", "/user/detail"]
147
- */
148
- specifiedPaths?: string[];
149
- /**
150
- * mock配置
151
- */
152
- mockConfig?: {
153
- /**
154
- * msw类型mock文件格式. 直接返回对象
155
- * 举例:
156
- * // @ts-ignore
157
-
158
- export default {
159
- 'DELETE /mydata/delete': { message: { message: 'Mydata successfully deleted' } },
160
- };
161
-
162
-
163
- 原文件:
164
- // @ts-ignore
165
- import { Request, Response } from 'express';
166
-
167
- export default {
168
- 'DELETE /mydata/delete': (req: Request, res: Response) => {
169
- res.status(200).send({ message: { message: 'Mydata successfully deleted' } });
170
- },
171
- };
172
- */
173
- msw?: boolean;
174
- };
175
- };
176
-
177
- const converterSwaggerToOpenApi = (swagger: any) => {
178
- if (!swagger.swagger) {
179
- return swagger;
180
- }
181
- return new Promise((resolve, reject) => {
182
- converter.convertObj(swagger, {}, (err: any, options: any) => {
183
- Log(["💺 将 Swagger 转化为 openAPI"]);
184
- if (err) {
185
- reject(err);
186
- return;
187
- }
188
- resolve(options.openapi);
189
- });
190
- });
191
- };
192
-
193
- export const getSchema = async (schemaPath: string, authorization?: string) => {
194
- if (schemaPath.startsWith("http")) {
195
- const protocol = schemaPath.startsWith("https:") ? https : http;
196
- try {
197
- const agent = new protocol.Agent({
198
- rejectUnauthorized: false,
199
- });
200
- const headers: Record<string, string> = {};
201
- if (authorization) {
202
- headers.authorization = authorization;
203
- }
204
- const json = await fetch(schemaPath, { agent, headers }).then((rest: any) => rest.json());
205
- return json;
206
- } catch (error) {
207
- console.log("fetch openapi error:", error);
208
- }
209
- return null;
210
- }
211
- const raw = readFileSync(schemaPath, "utf-8");
212
- return JSON.parse(raw);
213
- };
214
-
215
- const getOpenAPIConfig = async (schemaPath: string, authorization?: string) => {
216
- const schema = await getSchema(schemaPath, authorization);
217
- if (!schema) {
218
- return null;
219
- }
220
- fs.writeFileSync("debug-output.json", JSON.stringify(schema, null, 2));
221
-
222
- // console.dir(schema, { depth: null });
223
-
224
- const openAPI = await converterSwaggerToOpenApi(schema);
225
- return openAPI;
226
- };
227
-
228
- // 从 appName 生成 service 数据
229
- const _ttOpenAPI = async ({
230
- authorization,
231
- requestLibPath,
232
- schemaPath,
233
- mockFolder,
234
- nullable = false,
235
- requestOptionsType = "{[key: string]: any}",
236
- ...rest
237
- }: GenerateServiceProps) => {
238
- const requestImportStatement = getImportStatement(requestLibPath!);
239
-
240
- const config = {
241
- namespace: "API" as string,
242
- requestOptionsType,
243
- requestImportStatement,
244
- enumStyle: "string-literal" as const,
245
- nullable,
246
- isCamelCase: true,
247
- mockConfig: {},
248
- ...rest,
249
- };
250
-
251
- if (rest.specifiedPaths?.length) {
252
- Log([`🔄 指定更新: ${rest.projectName} (${rest.specifiedPaths.length} 个接口)`]);
253
- }
254
-
255
- const openAPI = await getOpenAPIConfig(schemaPath!, authorization);
256
- if (!openAPI) {
257
- Log([`⚠️ 获取文档失败: ${schemaPath}`]);
258
- return;
259
- }
260
-
261
- const serviceGenerator = new ServiceGenerator(config, openAPI);
262
- await serviceGenerator.genFile();
263
-
264
- if (mockFolder && !rest.specifiedPaths?.length) {
265
- await mockGenerator({
266
- openAPI,
267
- mockFolder: mockFolder || "./mocks/",
268
- mockConfig: rest.mockConfig || {},
269
- });
270
- }
271
- };
272
-
273
- export const ttOpenAPI = async (configs: GenerateServiceProps[] | GenerateServiceProps) => {
274
- const configList = Array.isArray(configs) ? configs : [configs];
275
-
276
- for (const config of configList) {
277
- await _ttOpenAPI(config);
278
- }
279
- };
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
+ * 指定生成的接口路径列表
144
+ * 传入则只生成这些接口,不传则全量生成
145
+ * @example specifiedPaths: ["/user/list", "/user/detail"]
146
+ */
147
+ specifiedPaths?: string[];
148
+ /**
149
+ * mock配置
150
+ */
151
+ mockConfig?: {
152
+ /**
153
+ * msw类型mock文件格式. 直接返回对象
154
+ * 举例:
155
+ * // @ts-ignore
156
+
157
+ export default {
158
+ 'DELETE /mydata/delete': { message: { message: 'Mydata successfully deleted' } },
159
+ };
160
+
161
+
162
+ 原文件:
163
+ // @ts-ignore
164
+ import { Request, Response } from 'express';
165
+
166
+ export default {
167
+ 'DELETE /mydata/delete': (req: Request, res: Response) => {
168
+ res.status(200).send({ message: { message: 'Mydata successfully deleted' } });
169
+ },
170
+ };
171
+ */
172
+ msw?: boolean;
173
+ };
174
+ };
175
+
176
+ const converterSwaggerToOpenApi = (swagger: any) => {
177
+ if (!swagger.swagger) {
178
+ return swagger;
179
+ }
180
+ return new Promise((resolve, reject) => {
181
+ converter.convertObj(swagger, {}, (err: any, options: any) => {
182
+ Log(["💺 将 Swagger 转化为 openAPI"]);
183
+ if (err) {
184
+ reject(err);
185
+ return;
186
+ }
187
+ resolve(options.openapi);
188
+ });
189
+ });
190
+ };
191
+
192
+ export const getSchema = async (schemaPath: string, authorization?: string) => {
193
+ if (schemaPath.startsWith("http")) {
194
+ const protocol = schemaPath.startsWith("https:") ? https : http;
195
+ try {
196
+ const agent = new protocol.Agent({
197
+ rejectUnauthorized: false,
198
+ });
199
+ const headers: Record<string, string> = {};
200
+ if (authorization) {
201
+ headers.authorization = authorization;
202
+ }
203
+ const json = await fetch(schemaPath, { agent, headers }).then((rest: any) => rest.json());
204
+ return json;
205
+ } catch (error) {
206
+ console.log("fetch openapi error:", error);
207
+ }
208
+ return null;
209
+ }
210
+ const raw = readFileSync(schemaPath, "utf-8");
211
+ return JSON.parse(raw);
212
+ };
213
+
214
+ const getOpenAPIConfig = async (schemaPath: string, authorization?: string) => {
215
+ const schema = await getSchema(schemaPath, authorization);
216
+ if (!schema) {
217
+ return null;
218
+ }
219
+ const openAPI = await converterSwaggerToOpenApi(schema);
220
+ return openAPI;
221
+ };
222
+
223
+ // 从 appName 生成 service 数据
224
+ const _ttOpenAPI = async ({
225
+ authorization,
226
+ requestLibPath,
227
+ schemaPath,
228
+ mockFolder,
229
+ nullable = false,
230
+ requestOptionsType = "{[key: string]: any}",
231
+ ...rest
232
+ }: GenerateServiceProps) => {
233
+ const requestImportStatement = getImportStatement(requestLibPath!);
234
+
235
+ const config = {
236
+ namespace: "API" as string,
237
+ requestOptionsType,
238
+ requestImportStatement,
239
+ enumStyle: "string-literal" as const,
240
+ nullable,
241
+ isCamelCase: true,
242
+ mockConfig: {},
243
+ ...rest,
244
+ };
245
+
246
+ if (rest.specifiedPaths?.length) {
247
+ Log([`🔄 指定更新: ${rest.projectName} (${rest.specifiedPaths.length} 个接口)`]);
248
+ }
249
+
250
+ const openAPI = await getOpenAPIConfig(schemaPath!, authorization);
251
+ if (!openAPI) {
252
+ Log([`⚠️ 获取文档失败: ${schemaPath}`]);
253
+ return;
254
+ }
255
+
256
+ const serviceGenerator = new ServiceGenerator(config, openAPI);
257
+ await serviceGenerator.genFile();
258
+
259
+ if (mockFolder && !rest.specifiedPaths?.length) {
260
+ await mockGenerator({
261
+ openAPI,
262
+ mockFolder: mockFolder || "./mocks/",
263
+ mockConfig: rest.mockConfig || {},
264
+ });
265
+ }
266
+ };
267
+
268
+ export const ttOpenAPI = async (configs: GenerateServiceProps[] | GenerateServiceProps) => {
269
+ const configList = Array.isArray(configs) ? configs : [configs];
270
+
271
+ for (const config of configList) {
272
+ await _ttOpenAPI(config);
273
+ }
274
+ };