@dazhicheng/openapi 1.1.2 → 1.1.4

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,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
- 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
+ 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
+ };
@@ -240,8 +240,8 @@ export const getGenInfo = (isDirExist: boolean, appName: string, absSrcPath: str
240
240
  return [
241
241
  true,
242
242
  !(
243
- existsSync(join(absSrcPath, BASE_DIRS[0], appName, "openAPI")) ||
244
- existsSync(join(absSrcPath, BASE_DIRS[1], appName, "openAPI"))
243
+ existsSync(join(absSrcPath, BASE_DIRS[0]!, appName, "openAPI")) ||
244
+ existsSync(join(absSrcPath, BASE_DIRS[1]!, appName, "openAPI"))
245
245
  ),
246
246
  ];
247
247
  };
@@ -305,6 +305,7 @@ class ServiceGenerator {
305
305
  }
306
306
 
307
307
  const pathItem: PathItemObject = this.openAPIData.paths[p];
308
+
308
309
  ["get", "put", "post", "delete", "patch"].forEach(method => {
309
310
  const operationObject: OperationObject = pathItem[method];
310
311
  if (!operationObject) {
@@ -337,6 +338,8 @@ class ServiceGenerator {
337
338
  try {
338
339
  const finalPath = join(basePath, this.config.projectName!);
339
340
  this.finalPath = finalPath;
341
+ console.log(glob.sync(`${finalPath}/**/*`), "xxxxxxxxx");
342
+
340
343
  glob
341
344
  .sync(`${finalPath}/**/*`)
342
345
  .filter(ele => !ele.includes("_deperated"))
@@ -358,6 +361,8 @@ class ServiceGenerator {
358
361
  // 生成 controller 文件
359
362
  const prettierError = [];
360
363
  for (const tp of this.getServiceTP()) {
364
+ // console.log("tp", tp);
365
+
361
366
  const template = "serviceController";
362
367
  const hasError = await this.genFileFromTemplate(this.getFinalFileName(`${tp.className}.ts`), template, {
363
368
  namespace: this.config.namespace,
package/src/util.ts CHANGED
@@ -29,6 +29,7 @@ export const prettierFile = async (content: string): Promise<[string, boolean]>
29
29
  result = await prettier.format(content, {
30
30
  parser: "typescript",
31
31
  ...prettierOptions,
32
+ singleQuote: true,
32
33
  });
33
34
  } catch (error: any) {
34
35
  console.error("Prettier error:", error);