openapi-ts-request 1.0.1 → 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/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  - 客户端请求函数(支持任意客户端)
11
11
  - 模拟请求响应服务
12
12
  - 枚举和枚举翻译
13
- - react-query
13
+ - react-query/vue-query
14
14
  - 类型字段翻译
15
15
  - JSON Schemas
16
16
 
@@ -19,7 +19,7 @@
19
19
  ## 功能
20
20
 
21
21
  - 支持 Swagger2.0/OpenAPI/Apifox 3.0,3.1 定义
22
- - 生成 TypeScript/JavaScript, 请求客户端(支持任意客户端), 请求模拟服务, 枚举和枚举翻译, react-query, 类型字段翻译, JSON Schemas
22
+ - 生成 TypeScript/JavaScript, 请求客户端(支持任意客户端), 请求模拟服务, 枚举和枚举翻译, react-query/vue-query, 类型字段翻译, JSON Schemas
23
23
  - 支持通过 npx、CLI、Nodejs 的方式使用
24
24
  - 支持自定义请求工具函数, 支持 Fetch、Axios、[UniApp-Request](https://github.com/openapi-ui/openapi-ts-request/issues/46)、Taro-Request、Node.js、XHR 客户端
25
25
  - 支持通过 tags 过滤生成结果
@@ -195,6 +195,7 @@ $ openapi --help
195
195
  --requestImportStatement <string> custom request import statement, for example: "const request = require('@/request')"
196
196
  --apiPrefix <string> custom the prefix of the api path, for example: "api"(variable), "'api'"(string)
197
197
  --isGenReactQuery <boolean> generate react-query (default: false)
198
+ --reactQueryMode <string> react-query mode, react/vue (default: "react")
198
199
  --isGenJavaScript <boolean> generate JavaScript (default: false)
199
200
  --isDisplayTypeLabel <boolean> generate label matching type field (default: false)
200
201
  --isGenJsonSchemas <boolean> generate JSON Schemas (default: false)
@@ -230,6 +231,7 @@ openapi --i ./spec.json --o ./apis
230
231
  | requestImportStatement | 否 | string | - | 自定义请求方法表达式,例如:"const request = require('@/request')" |
231
232
  | apiPrefix | 否 | string | - | api path的前缀,例如:'api'(动态变量), "'api'"(字符串) |
232
233
  | isGenReactQuery | 否 | boolean | false | 是否生成 react-query |
234
+ | reactQueryMode | 否 | string | 'react' | react-query 模式,可选 react/vue |
233
235
  | isGenJavaScript | 否 | boolean | false | 是否生成 JavaScript |
234
236
  | isDisplayTypeLabel | 否 | boolean | false | 是否生成 type 对应的label |
235
237
  | isGenJsonSchemas | 否 | boolean | false | 是否生成 JSON Schemas |
@@ -24,6 +24,7 @@ const params = commander_1.program
24
24
  .option('--requestImportStatement <string>', `custom request import statement, for example: "const request = require('@/request')"`)
25
25
  .option('--apiPrefix <string>', `custom the prefix of the api path, for example: "api"(variable), "'api'"(string)`)
26
26
  .option('--isGenReactQuery <boolean>', 'generate react-query', false)
27
+ .option('--reactQueryMode <string>', 'react-query mode, react/vue (default: "react")')
27
28
  .option('--isGenJavaScript <boolean>', 'generate JavaScript', false)
28
29
  .option('--isDisplayTypeLabel <boolean>', 'generate label matching type field', false)
29
30
  .option('--isGenJsonSchemas <boolean>', 'generate JSON Schemas', false)
@@ -60,6 +61,7 @@ function run() {
60
61
  requestOptionsType: params.requestOptionsType,
61
62
  apiPrefix: params.apiPrefix,
62
63
  isGenReactQuery: JSON.parse(params.isGenReactQuery) === true,
64
+ reactQueryMode: params.reactQueryMode,
63
65
  isGenJavaScript: JSON.parse(params.isGenJavaScript) === true,
64
66
  isDisplayTypeLabel: JSON.parse(params.isDisplayTypeLabel) === true,
65
67
  isGenJsonSchemas: JSON.parse(params.isGenJsonSchemas) === true,
@@ -0,0 +1,36 @@
1
+ import { IReactQueryMode } from './type';
2
+ export declare enum SchemaObjectFormat {
3
+ int32 = "int32",
4
+ int64 = "int64",
5
+ float = "float",
6
+ double = "double",
7
+ byte = "byte",
8
+ binary = "binary",
9
+ date = "date",
10
+ dateTime = "date-time",
11
+ password = "password",
12
+ base64 = "base64"
13
+ }
14
+ export declare enum SchemaObjectType {
15
+ array = "array",
16
+ stringArray = "string[]",
17
+ boolean = "boolean",
18
+ object = "object",
19
+ number = "number",
20
+ string = "string",
21
+ integer = "integer",
22
+ enum = "enum",
23
+ null = "null",
24
+ union = "union",
25
+ file = "file"
26
+ }
27
+ export declare enum PriorityRule {
28
+ include = "include",
29
+ exclude = "exclude",
30
+ both = "both"
31
+ }
32
+ export declare enum ReactQueryMode {
33
+ react = "react",
34
+ vue = "vue"
35
+ }
36
+ export declare const displayReactQueryMode: (mode: IReactQueryMode) => string;
package/dist/config.js ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.displayReactQueryMode = exports.ReactQueryMode = exports.PriorityRule = exports.SchemaObjectType = exports.SchemaObjectFormat = void 0;
4
+ var SchemaObjectFormat;
5
+ (function (SchemaObjectFormat) {
6
+ SchemaObjectFormat["int32"] = "int32";
7
+ SchemaObjectFormat["int64"] = "int64";
8
+ SchemaObjectFormat["float"] = "float";
9
+ SchemaObjectFormat["double"] = "double";
10
+ SchemaObjectFormat["byte"] = "byte";
11
+ SchemaObjectFormat["binary"] = "binary";
12
+ SchemaObjectFormat["date"] = "date";
13
+ SchemaObjectFormat["dateTime"] = "date-time";
14
+ SchemaObjectFormat["password"] = "password";
15
+ SchemaObjectFormat["base64"] = "base64";
16
+ })(SchemaObjectFormat || (exports.SchemaObjectFormat = SchemaObjectFormat = {}));
17
+ var SchemaObjectType;
18
+ (function (SchemaObjectType) {
19
+ SchemaObjectType["array"] = "array";
20
+ SchemaObjectType["stringArray"] = "string[]";
21
+ SchemaObjectType["boolean"] = "boolean";
22
+ SchemaObjectType["object"] = "object";
23
+ SchemaObjectType["number"] = "number";
24
+ SchemaObjectType["string"] = "string";
25
+ SchemaObjectType["integer"] = "integer";
26
+ SchemaObjectType["enum"] = "enum";
27
+ SchemaObjectType["null"] = "null";
28
+ SchemaObjectType["union"] = "union";
29
+ SchemaObjectType["file"] = "file";
30
+ })(SchemaObjectType || (exports.SchemaObjectType = SchemaObjectType = {}));
31
+ var PriorityRule;
32
+ (function (PriorityRule) {
33
+ PriorityRule["include"] = "include";
34
+ PriorityRule["exclude"] = "exclude";
35
+ PriorityRule["both"] = "both";
36
+ })(PriorityRule || (exports.PriorityRule = PriorityRule = {}));
37
+ var ReactQueryMode;
38
+ (function (ReactQueryMode) {
39
+ ReactQueryMode["react"] = "react";
40
+ ReactQueryMode["vue"] = "vue";
41
+ })(ReactQueryMode || (exports.ReactQueryMode = ReactQueryMode = {}));
42
+ const displayReactQueryMode = (mode) => {
43
+ return {
44
+ react: '@tanstack/react-query',
45
+ vue: '@tanstack/vue-query',
46
+ }[mode];
47
+ };
48
+ exports.displayReactQueryMode = displayReactQueryMode;
@@ -1,11 +1,11 @@
1
1
  import { Dictionary } from 'lodash';
2
- import { ParameterObject, SchemaObject } from '../type';
2
+ import { IReactQueryMode, ParameterObject, SchemaObject } from '../type';
3
3
  export declare const serviceEntryFileName = "index";
4
4
  export declare const interfaceFileName = "types";
5
5
  export declare const displayEnumLabelFileName = "displayEnumLabel";
6
6
  export declare const displayTypeLabelFileName = "displayTypeLabel";
7
7
  export declare const schemaFileName = "schema";
8
- export declare const reactQueryFileName = "reactquery";
8
+ export declare const displayReactQueryFileName: (reactQueryMode: IReactQueryMode) => string;
9
9
  export declare enum TypescriptFileType {
10
10
  interface = "interface",
11
11
  serviceController = "serviceController",
@@ -1,12 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LangType = exports.lineBreakReg = exports.numberEnum = exports.parametersIn = exports.parametersInsEnum = exports.methods = exports.DEFAULT_PATH_PARAM = exports.DEFAULT_SCHEMA = exports.TypescriptFileType = exports.reactQueryFileName = exports.schemaFileName = exports.displayTypeLabelFileName = exports.displayEnumLabelFileName = exports.interfaceFileName = exports.serviceEntryFileName = void 0;
3
+ exports.LangType = exports.lineBreakReg = exports.numberEnum = exports.parametersIn = exports.parametersInsEnum = exports.methods = exports.DEFAULT_PATH_PARAM = exports.DEFAULT_SCHEMA = exports.TypescriptFileType = exports.displayReactQueryFileName = exports.schemaFileName = exports.displayTypeLabelFileName = exports.displayEnumLabelFileName = exports.interfaceFileName = exports.serviceEntryFileName = void 0;
4
4
  exports.serviceEntryFileName = 'index';
5
5
  exports.interfaceFileName = 'types';
6
6
  exports.displayEnumLabelFileName = 'displayEnumLabel';
7
7
  exports.displayTypeLabelFileName = 'displayTypeLabel';
8
8
  exports.schemaFileName = 'schema';
9
- exports.reactQueryFileName = 'reactquery';
9
+ const displayReactQueryFileName = (reactQueryMode) => {
10
+ return {
11
+ react: 'reactquery',
12
+ vue: 'vuequery',
13
+ }[reactQueryMode];
14
+ };
15
+ exports.displayReactQueryFileName = displayReactQueryFileName;
10
16
  var TypescriptFileType;
11
17
  (function (TypescriptFileType) {
12
18
  TypescriptFileType["interface"] = "interface";
@@ -8,9 +8,9 @@ const minimatch_1 = require("minimatch");
8
8
  const nunjucks_1 = tslib_1.__importDefault(require("nunjucks"));
9
9
  const path_1 = require("path");
10
10
  const rimraf_1 = require("rimraf");
11
+ const config_1 = require("../config");
11
12
  const log_1 = tslib_1.__importDefault(require("../log"));
12
- const type_1 = require("../type");
13
- const config_1 = require("./config");
13
+ const config_2 = require("./config");
14
14
  const file_1 = require("./file");
15
15
  const patchSchema_1 = require("./patchSchema");
16
16
  const util_1 = require("./util");
@@ -26,7 +26,7 @@ class ServiceGenerator {
26
26
  const includePaths = ((_b = this.config) === null || _b === void 0 ? void 0 : _b.includePaths) || [];
27
27
  const excludeTags = ((_c = this.config) === null || _c === void 0 ? void 0 : _c.excludeTags) || [];
28
28
  const excludePaths = ((_d = this.config) === null || _d === void 0 ? void 0 : _d.excludePaths) || [];
29
- const priorityRule = type_1.PriorityRule[config.priorityRule];
29
+ const priorityRule = config_1.PriorityRule[config.priorityRule];
30
30
  if ((_e = this.config.hook) === null || _e === void 0 ? void 0 : _e.afterOpenApiDataInited) {
31
31
  this.openAPIData =
32
32
  this.config.hook.afterOpenApiDataInited(openAPIData) || openAPIData;
@@ -38,7 +38,7 @@ class ServiceGenerator {
38
38
  outerLoop: for (const pathKey in this.openAPIData.paths) {
39
39
  // 这里判断paths
40
40
  switch (priorityRule) {
41
- case type_1.PriorityRule.include: {
41
+ case config_1.PriorityRule.include: {
42
42
  // includePaths and includeTags is empty, 直接跳过
43
43
  if ((0, lodash_1.isEmpty)(includeTags) && (0, lodash_1.isEmpty)(includePaths)) {
44
44
  this.log('priorityRule include need includeTags or includePaths');
@@ -50,13 +50,13 @@ class ServiceGenerator {
50
50
  }
51
51
  break;
52
52
  }
53
- case type_1.PriorityRule.exclude: {
53
+ case config_1.PriorityRule.exclude: {
54
54
  if (this.validateRegexp(pathKey, excludePaths)) {
55
55
  continue;
56
56
  }
57
57
  break;
58
58
  }
59
- case type_1.PriorityRule.both: {
59
+ case config_1.PriorityRule.both: {
60
60
  // includePaths and includeTags is empty,直接跳过
61
61
  if ((0, lodash_1.isEmpty)(includeTags) && (0, lodash_1.isEmpty)(includePaths)) {
62
62
  this.log('priorityRule both need includeTags or includePaths');
@@ -75,7 +75,7 @@ class ServiceGenerator {
75
75
  throw new Error('priorityRule must be "include" or "exclude" or "include"');
76
76
  }
77
77
  const pathItem = this.openAPIData.paths[pathKey];
78
- (0, lodash_1.forEach)(config_1.methods, (method) => {
78
+ (0, lodash_1.forEach)(config_2.methods, (method) => {
79
79
  var _a;
80
80
  const operationObject = pathItem[method];
81
81
  if (!operationObject) {
@@ -89,7 +89,7 @@ class ServiceGenerator {
89
89
  return;
90
90
  }
91
91
  const tagLowerCase = tag.toLowerCase();
92
- if (priorityRule === type_1.PriorityRule.include) {
92
+ if (priorityRule === config_1.PriorityRule.include) {
93
93
  // includeTags 为空,不会匹配任何path,故跳过
94
94
  if ((0, lodash_1.isEmpty)(includeTags)) {
95
95
  this.log('priorityRule include need includeTags or includePaths');
@@ -99,12 +99,12 @@ class ServiceGenerator {
99
99
  return;
100
100
  }
101
101
  }
102
- if (priorityRule === type_1.PriorityRule.exclude) {
102
+ if (priorityRule === config_1.PriorityRule.exclude) {
103
103
  if (this.validateRegexp(tagLowerCase, excludeTags)) {
104
104
  return;
105
105
  }
106
106
  }
107
- if (priorityRule === type_1.PriorityRule.both) {
107
+ if (priorityRule === config_1.PriorityRule.both) {
108
108
  // includeTags is empty 没有配置, 直接跳过
109
109
  if ((0, lodash_1.isEmpty)(includeTags)) {
110
110
  this.log('priorityRule both need includeTags or includePaths');
@@ -142,12 +142,14 @@ class ServiceGenerator {
142
142
  }
143
143
  const isOnlyGenTypeScriptType = this.config.isOnlyGenTypeScriptType;
144
144
  const isGenJavaScript = this.config.isGenJavaScript;
145
+ const reactQueryMode = this.config.reactQueryMode;
146
+ const reactQueryFileName = (0, config_2.displayReactQueryFileName)(reactQueryMode);
145
147
  // 处理重复的 typeName
146
148
  const interfaceTPConfigs = this.getInterfaceTPConfigs();
147
149
  (0, util_1.handleDuplicateTypeNames)(interfaceTPConfigs);
148
150
  // 生成 ts 类型声明
149
151
  if (!isGenJavaScript) {
150
- this.genFileFromTemplate(`${config_1.interfaceFileName}.ts`, config_1.TypescriptFileType.interface, {
152
+ this.genFileFromTemplate(`${config_2.interfaceFileName}.ts`, config_2.TypescriptFileType.interface, {
151
153
  nullable: this.config.nullable,
152
154
  list: interfaceTPConfigs,
153
155
  });
@@ -155,10 +157,10 @@ class ServiceGenerator {
155
157
  // 生成枚举翻译
156
158
  const enums = (0, lodash_1.filter)(interfaceTPConfigs, (item) => item.isEnum);
157
159
  if (!isGenJavaScript && !isOnlyGenTypeScriptType && !(0, lodash_1.isEmpty)(enums)) {
158
- this.genFileFromTemplate(`${config_1.displayEnumLabelFileName}.ts`, config_1.TypescriptFileType.displayEnumLabel, {
160
+ this.genFileFromTemplate(`${config_2.displayEnumLabelFileName}.ts`, config_2.TypescriptFileType.displayEnumLabel, {
159
161
  list: enums,
160
162
  namespace: this.config.namespace,
161
- interfaceFileName: config_1.interfaceFileName,
163
+ interfaceFileName: config_2.interfaceFileName,
162
164
  });
163
165
  }
164
166
  const displayTypeLabels = (0, lodash_1.filter)(interfaceTPConfigs, (item) => !item.isEnum);
@@ -167,10 +169,10 @@ class ServiceGenerator {
167
169
  !isOnlyGenTypeScriptType &&
168
170
  this.config.isDisplayTypeLabel &&
169
171
  !(0, lodash_1.isEmpty)(displayTypeLabels)) {
170
- this.genFileFromTemplate(`${config_1.displayTypeLabelFileName}.ts`, config_1.TypescriptFileType.displayTypeLabel, {
172
+ this.genFileFromTemplate(`${config_2.displayTypeLabelFileName}.ts`, config_2.TypescriptFileType.displayTypeLabel, {
171
173
  list: displayTypeLabels,
172
174
  namespace: this.config.namespace,
173
- interfaceFileName: config_1.interfaceFileName,
175
+ interfaceFileName: config_2.interfaceFileName,
174
176
  });
175
177
  }
176
178
  if (!isOnlyGenTypeScriptType) {
@@ -179,12 +181,12 @@ class ServiceGenerator {
179
181
  this.getServiceTPConfigs().forEach((tp) => {
180
182
  const hasError = this.genFileFromTemplate(isGenJavaScript
181
183
  ? (0, util_1.getFinalFileName)(`${tp.className}.js`)
182
- : (0, util_1.getFinalFileName)(`${tp.className}.ts`), config_1.TypescriptFileType.serviceController, Object.assign({ namespace: this.config.namespace, requestOptionsType: this.config.requestOptionsType, requestImportStatement: this.config.requestImportStatement, interfaceFileName: config_1.interfaceFileName }, tp));
184
+ : (0, util_1.getFinalFileName)(`${tp.className}.ts`), config_2.TypescriptFileType.serviceController, Object.assign({ namespace: this.config.namespace, requestOptionsType: this.config.requestOptionsType, requestImportStatement: this.config.requestImportStatement, interfaceFileName: config_2.interfaceFileName }, tp));
183
185
  prettierError.push(hasError);
184
186
  if (this.config.isGenReactQuery) {
185
187
  this.genFileFromTemplate(isGenJavaScript
186
- ? (0, util_1.getFinalFileName)(`${tp.className}.${config_1.reactQueryFileName}.js`)
187
- : (0, util_1.getFinalFileName)(`${tp.className}.${config_1.reactQueryFileName}.ts`), config_1.TypescriptFileType.reactQuery, Object.assign({ namespace: this.config.namespace, requestOptionsType: this.config.requestOptionsType, requestImportStatement: this.config.requestImportStatement, interfaceFileName: config_1.interfaceFileName }, tp));
188
+ ? (0, util_1.getFinalFileName)(`${tp.className}.${reactQueryFileName}.js`)
189
+ : (0, util_1.getFinalFileName)(`${tp.className}.${reactQueryFileName}.ts`), config_2.TypescriptFileType.reactQuery, Object.assign({ namespace: this.config.namespace, requestOptionsType: this.config.requestOptionsType, requestImportStatement: this.config.requestImportStatement, interfaceFileName: config_2.interfaceFileName, reactQueryModePackageName: (0, config_1.displayReactQueryMode)(reactQueryMode) }, tp));
188
190
  }
189
191
  });
190
192
  if (prettierError.includes(true)) {
@@ -197,30 +199,30 @@ class ServiceGenerator {
197
199
  // 处理重复的 schemaName
198
200
  (0, util_1.handleDuplicateTypeNames)(this.schemaList);
199
201
  // 生成 schema 文件
200
- this.genFileFromTemplate(isGenJavaScript ? `${config_1.schemaFileName}.js` : `${config_1.schemaFileName}.ts`, config_1.TypescriptFileType.schema, {
202
+ this.genFileFromTemplate(isGenJavaScript ? `${config_2.schemaFileName}.js` : `${config_2.schemaFileName}.ts`, config_2.TypescriptFileType.schema, {
201
203
  list: this.schemaList,
202
204
  });
203
205
  }
204
206
  // 生成 service index 文件
205
207
  this.genFileFromTemplate(isGenJavaScript
206
- ? `${config_1.serviceEntryFileName}.js`
207
- : `${config_1.serviceEntryFileName}.ts`, config_1.TypescriptFileType.serviceIndex, {
208
+ ? `${config_2.serviceEntryFileName}.js`
209
+ : `${config_2.serviceEntryFileName}.ts`, config_2.TypescriptFileType.serviceIndex, {
208
210
  list: this.classNameList,
209
211
  namespace: this.config.namespace,
210
- interfaceFileName: config_1.interfaceFileName,
211
- genType: isGenJavaScript ? config_1.LangType.js : config_1.LangType.ts,
212
+ interfaceFileName: config_2.interfaceFileName,
213
+ genType: isGenJavaScript ? config_2.LangType.js : config_2.LangType.ts,
212
214
  isGenJsonSchemas: !isOnlyGenTypeScriptType &&
213
215
  this.config.isGenJsonSchemas &&
214
216
  !(0, lodash_1.isEmpty)(this.schemaList),
215
- schemaFileName: config_1.schemaFileName,
217
+ schemaFileName: config_2.schemaFileName,
216
218
  isDisplayEnumLabel: !isOnlyGenTypeScriptType && !(0, lodash_1.isEmpty)(enums),
217
- displayEnumLabelFileName: config_1.displayEnumLabelFileName,
219
+ displayEnumLabelFileName: config_2.displayEnumLabelFileName,
218
220
  isGenReactQuery: this.config.isGenReactQuery,
219
- reactQueryFileName: config_1.reactQueryFileName,
221
+ reactQueryFileName,
220
222
  isDisplayTypeLabel: !isOnlyGenTypeScriptType &&
221
223
  this.config.isDisplayTypeLabel &&
222
224
  !(0, lodash_1.isEmpty)(displayTypeLabels),
223
- displayTypeLabelFileName: config_1.displayTypeLabelFileName,
225
+ displayTypeLabelFileName: config_2.displayTypeLabelFileName,
224
226
  });
225
227
  // 打印日志
226
228
  (0, log_1.default)('✅ 成功生成 api 文件');
@@ -233,7 +235,7 @@ class ServiceGenerator {
233
235
  // 强行替换掉请求参数params的类型,生成方法对应的 xxxxParams 类型
234
236
  (0, lodash_1.keys)(this.openAPIData.paths).forEach((pathKey) => {
235
237
  const pathItem = this.openAPIData.paths[pathKey];
236
- (0, lodash_1.forEach)(config_1.methods, (method) => {
238
+ (0, lodash_1.forEach)(config_2.methods, (method) => {
237
239
  var _a, _b, _c, _d;
238
240
  const operationObject = pathItem[method];
239
241
  const hookCustomFileNames = ((_a = this.config.hook) === null || _a === void 0 ? void 0 : _a.customFileNames) || util_1.getDefaultFileTag;
@@ -250,13 +252,13 @@ class ServiceGenerator {
250
252
  }
251
253
  // 筛选出 pathItem 包含的 $ref 对应的schema
252
254
  (0, util_1.markAllowedSchema)(JSON.stringify(pathItem), this.openAPIData);
253
- operationObject.parameters = (_b = operationObject.parameters) === null || _b === void 0 ? void 0 : _b.filter((item) => (item === null || item === void 0 ? void 0 : item.in) !== `${config_1.parametersInsEnum.header}`);
255
+ operationObject.parameters = (_b = operationObject.parameters) === null || _b === void 0 ? void 0 : _b.filter((item) => (item === null || item === void 0 ? void 0 : item.in) !== `${config_2.parametersInsEnum.header}`);
254
256
  const props = [];
255
257
  (_c = operationObject.parameters) === null || _c === void 0 ? void 0 : _c.forEach((parameter) => {
256
258
  var _a;
257
259
  props.push({
258
260
  name: parameter.name,
259
- desc: ((_a = parameter.description) !== null && _a !== void 0 ? _a : '').replace(config_1.lineBreakReg, ''),
261
+ desc: ((_a = parameter.description) !== null && _a !== void 0 ? _a : '').replace(config_2.lineBreakReg, ''),
260
262
  required: parameter.required || false,
261
263
  type: this.getType(parameter.schema),
262
264
  });
@@ -266,7 +268,7 @@ class ServiceGenerator {
266
268
  var _a;
267
269
  props.push({
268
270
  name: parameter.name,
269
- desc: ((_a = parameter.description) !== null && _a !== void 0 ? _a : '').replace(config_1.lineBreakReg, ''),
271
+ desc: ((_a = parameter.description) !== null && _a !== void 0 ? _a : '').replace(config_2.lineBreakReg, ''),
270
272
  required: parameter.required,
271
273
  type: this.getType(parameter.schema),
272
274
  });
@@ -293,9 +295,9 @@ class ServiceGenerator {
293
295
  const getDefinesType = () => {
294
296
  if (result === null || result === void 0 ? void 0 : result.type) {
295
297
  return schema.type === 'object'
296
- ? type_1.SchemaObjectType.object
297
- : config_1.numberEnum.includes(result.type)
298
- ? type_1.SchemaObjectType.number
298
+ ? config_1.SchemaObjectType.object
299
+ : config_2.numberEnum.includes(result.type)
300
+ ? config_1.SchemaObjectType.number
299
301
  : result.type;
300
302
  }
301
303
  return 'Record<string, unknown>';
@@ -418,7 +420,7 @@ class ServiceGenerator {
418
420
  : functionName, typeName: this.getFunctionParamsTypeName(newApi), path: getPrefixPath(), pathInComment: formattedPath.replace(/\*/g, '&#42;'), apifoxRunLink: newApi === null || newApi === void 0 ? void 0 : newApi['x-run-in-apifox'], hasPathVariables: formattedPath.includes('{'), hasApiPrefix: !!this.config.apiPrefix, method: newApi.method,
419
421
  // 如果 functionName 和 summary 相同,则不显示 summary
420
422
  desc: functionName === newApi.summary
421
- ? (newApi.description || '').replace(config_1.lineBreakReg, '')
423
+ ? (newApi.description || '').replace(config_2.lineBreakReg, '')
422
424
  : [
423
425
  newApi.summary,
424
426
  newApi.description,
@@ -428,7 +430,7 @@ class ServiceGenerator {
428
430
  ]
429
431
  .filter((s) => s)
430
432
  .join(' ')
431
- .replace(config_1.lineBreakReg, ''), hasHeader: !!(params === null || params === void 0 ? void 0 : params.header) || !!(body === null || body === void 0 ? void 0 : body.mediaType), params: finalParams, hasParams: Boolean((0, lodash_1.keys)(finalParams).length), options: ((_f = (_e = this.config.hook) === null || _e === void 0 ? void 0 : _e.customOptionsDefaultValue) === null || _f === void 0 ? void 0 : _f.call(_e, newApi)) || {}, body,
433
+ .replace(config_2.lineBreakReg, ''), hasHeader: !!(params === null || params === void 0 ? void 0 : params.header) || !!(body === null || body === void 0 ? void 0 : body.mediaType), params: finalParams, hasParams: Boolean((0, lodash_1.keys)(finalParams).length), options: ((_f = (_e = this.config.hook) === null || _e === void 0 ? void 0 : _e.customOptionsDefaultValue) === null || _f === void 0 ? void 0 : _f.call(_e, newApi)) || {}, body,
432
434
  file, hasFormData: formData, response });
433
435
  }
434
436
  catch (error) {
@@ -450,7 +452,7 @@ class ServiceGenerator {
450
452
  });
451
453
  }
452
454
  return {
453
- genType: this.config.isGenJavaScript ? config_1.LangType.js : config_1.LangType.ts,
455
+ genType: this.config.isGenJavaScript ? config_2.LangType.js : config_2.LangType.ts,
454
456
  className,
455
457
  instanceName: `${(_b = fileName[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase()}${fileName.slice(1)}`,
456
458
  list: genParams,
@@ -519,7 +521,7 @@ class ServiceGenerator {
519
521
  return null;
520
522
  }
521
523
  let mediaType = (0, lodash_1.keys)(reqContent)[0];
522
- const schema = ((_a = reqContent[mediaType]) === null || _a === void 0 ? void 0 : _a.schema) || config_1.DEFAULT_SCHEMA;
524
+ const schema = ((_a = reqContent[mediaType]) === null || _a === void 0 ? void 0 : _a.schema) || config_2.DEFAULT_SCHEMA;
523
525
  if (mediaType === '*/*') {
524
526
  mediaType = '';
525
527
  }
@@ -531,7 +533,7 @@ class ServiceGenerator {
531
533
  var _a, _b;
532
534
  const propertyObj = schema.properties[propertyKey];
533
535
  if (propertyObj &&
534
- ![type_1.SchemaObjectFormat.binary, type_1.SchemaObjectFormat.base64].includes(propertyObj.format) &&
536
+ ![config_1.SchemaObjectFormat.binary, config_1.SchemaObjectFormat.base64].includes(propertyObj.format) &&
535
537
  !(0, util_1.isBinaryArraySchemaObject)(propertyObj)) {
536
538
  // 测试了很多用例,很少有用例走到这里
537
539
  return {
@@ -574,8 +576,8 @@ class ServiceGenerator {
574
576
  // 这里 p.type 是自定义type, 注意别混淆
575
577
  return {
576
578
  title: p.name,
577
- multiple: p.type === `${type_1.SchemaObjectType.array}` ||
578
- p.type === `${type_1.SchemaObjectType.stringArray}`,
579
+ multiple: p.type === `${config_1.SchemaObjectType.array}` ||
580
+ p.type === `${config_1.SchemaObjectType.stringArray}`,
579
581
  };
580
582
  });
581
583
  }
@@ -604,7 +606,7 @@ class ServiceGenerator {
604
606
  return defaultResponse;
605
607
  }
606
608
  let schema = (resContent[mediaType].schema ||
607
- config_1.DEFAULT_SCHEMA);
609
+ config_2.DEFAULT_SCHEMA);
608
610
  if ((0, util_1.isReferenceObject)(schema)) {
609
611
  const refName = (0, util_1.getLastRefName)(schema.$ref);
610
612
  const childrenSchema = components.schemas[refName];
@@ -613,7 +615,7 @@ class ServiceGenerator {
613
615
  .map((field) => childrenSchema.properties[field])
614
616
  .filter(Boolean)) === null || _a === void 0 ? void 0 : _a[0]) ||
615
617
  resContent[mediaType].schema ||
616
- config_1.DEFAULT_SCHEMA);
618
+ config_2.DEFAULT_SCHEMA);
617
619
  }
618
620
  }
619
621
  if ((0, util_1.isSchemaObject)(schema)) {
@@ -631,7 +633,7 @@ class ServiceGenerator {
631
633
  getParamsTP(parameters = [], path = null) {
632
634
  const templateParams = {};
633
635
  if (parameters === null || parameters === void 0 ? void 0 : parameters.length) {
634
- (0, lodash_1.forEach)(config_1.parametersIn, (source) => {
636
+ (0, lodash_1.forEach)(config_2.parametersIn, (source) => {
635
637
  const params = parameters
636
638
  .map((p) => this.resolveRefObject(p))
637
639
  .filter((p) => p.in === source)
@@ -644,7 +646,7 @@ class ServiceGenerator {
644
646
  const deRefObj = (0, lodash_1.entries)((_c = this.openAPIData.components) === null || _c === void 0 ? void 0 : _c.schemas).find(([k]) => k === refName) || [];
645
647
  const isRefObject = ((_d = deRefObj[1]) === null || _d === void 0 ? void 0 : _d.type) === 'object' &&
646
648
  !(0, lodash_1.isEmpty)((_e = deRefObj[1]) === null || _e === void 0 ? void 0 : _e.properties);
647
- return Object.assign(Object.assign({}, p), { isObject: isDirectObject || isRefObject, type: this.getType(p.schema || config_1.DEFAULT_SCHEMA, this.config.namespace) });
649
+ return Object.assign(Object.assign({}, p), { isObject: isDirectObject || isRefObject, type: this.getType(p.schema || config_2.DEFAULT_SCHEMA, this.config.namespace) });
648
650
  });
649
651
  if (params.length) {
650
652
  templateParams[source] = params;
@@ -657,7 +659,7 @@ class ServiceGenerator {
657
659
  let match = null;
658
660
  while ((match = regex.exec(path))) {
659
661
  if (!templateParams.path.some((p) => p.name === match[1])) {
660
- templateParams.path.push(Object.assign(Object.assign({}, config_1.DEFAULT_PATH_PARAM), { name: match[1] }));
662
+ templateParams.path.push(Object.assign(Object.assign({}, config_2.DEFAULT_PATH_PARAM), { name: match[1] }));
661
663
  }
662
664
  }
663
665
  // 如果 path 没有内容,则将删除 path 参数,避免影响后续的 hasParams 判断
@@ -717,7 +719,7 @@ class ServiceGenerator {
717
719
  const enumArray = schemaObject.enum;
718
720
  let enumStr = '';
719
721
  let enumLabelTypeStr = '';
720
- if (config_1.numberEnum.includes(schemaObject.type) || (0, util_1.isAllNumber)(enumArray)) {
722
+ if (config_2.numberEnum.includes(schemaObject.type) || (0, util_1.isAllNumber)(enumArray)) {
721
723
  enumStr = `{${(0, lodash_1.map)(enumArray, (value) => `"NUMBER_${value}"=${Number(value)}`).join(',')}}`;
722
724
  }
723
725
  else if ((0, util_1.isAllNumeric)(enumArray)) {
@@ -747,7 +749,7 @@ class ServiceGenerator {
747
749
  }).join(',')}}`;
748
750
  }
749
751
  else {
750
- if (config_1.numberEnum.includes(schemaObject.type) || (0, util_1.isAllNumber)(enumArray)) {
752
+ if (config_2.numberEnum.includes(schemaObject.type) || (0, util_1.isAllNumber)(enumArray)) {
751
753
  enumLabelTypeStr = `{${(0, lodash_1.map)(enumArray, (value) => `"NUMBER_${value}":${Number(value)}`).join(',')}}`;
752
754
  }
753
755
  else if ((0, util_1.isAllNumeric)(enumArray)) {
@@ -781,7 +783,7 @@ class ServiceGenerator {
781
783
  const requiredPropKeys = (_a = schemaObject === null || schemaObject === void 0 ? void 0 : schemaObject.required) !== null && _a !== void 0 ? _a : false;
782
784
  const properties = schemaObject.properties;
783
785
  return (0, lodash_1.keys)(properties).map((propKey) => {
784
- const schema = ((properties === null || properties === void 0 ? void 0 : properties[propKey]) || config_1.DEFAULT_SCHEMA);
786
+ const schema = ((properties === null || properties === void 0 ? void 0 : properties[propKey]) || config_2.DEFAULT_SCHEMA);
785
787
  // 剔除属性键值中的特殊符号,因为函数入参变量存在特殊符号会导致解析文件失败
786
788
  // eslint-disable-next-line no-useless-escape
787
789
  propKey = propKey.replace(/[\[|\]]/g, '');
@@ -789,7 +791,7 @@ class ServiceGenerator {
789
791
  return Object.assign(Object.assign({}, schema), { name: propKey, type: this.getType(schema), desc: [schema.title, schema.description]
790
792
  .filter((item) => item)
791
793
  .join(' ')
792
- .replace(config_1.lineBreakReg, ''),
794
+ .replace(config_2.lineBreakReg, ''),
793
795
  // 如果没有 required 信息,默认全部是非必填
794
796
  required: requiredPropKeys
795
797
  ? requiredPropKeys.some((key) => key === propKey)
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { APIDataType } from './generator/type';
2
- import { ComponentsObject, OpenAPIObject, OperationObject, ReferenceObject, SchemaObject } from './type';
2
+ import { ComponentsObject, IPriorityRule, IReactQueryMode, OpenAPIObject, OperationObject, ReferenceObject, SchemaObject } from './type';
3
3
  export * from './generator/patchSchema';
4
4
  export type GenerateServiceProps = {
5
5
  /**
@@ -25,7 +25,7 @@ export type GenerateServiceProps = {
25
25
  /**
26
26
  * 优先规则, include(只允许include列表) | exclude(只排除exclude列表) | both(允许include列表,排除exclude列表)
27
27
  */
28
- priorityRule?: string;
28
+ priorityRule?: IPriorityRule;
29
29
  /**
30
30
  * 只解析归属于 tags 集合的 api 和 schema
31
31
  */
@@ -64,6 +64,10 @@ export type GenerateServiceProps = {
64
64
  * 是否生成 react-query 配置
65
65
  */
66
66
  isGenReactQuery?: boolean;
67
+ /**
68
+ * reactQuery 模式
69
+ */
70
+ reactQueryMode?: IReactQueryMode;
67
71
  /**
68
72
  * 是否生成 JavaScript, 不生成 TypeScript
69
73
  */
@@ -172,4 +176,4 @@ export type GenerateServiceProps = {
172
176
  customFileNames?: (operationObject: OperationObject, apiPath: string, apiMethod: string) => string[] | null;
173
177
  };
174
178
  };
175
- export declare function generateService({ requestLibPath, schemaPath, mockFolder, includeTags, excludeTags, authorization, isTranslateToEnglishTag, priorityRule, ...rest }: GenerateServiceProps): Promise<void>;
179
+ export declare function generateService({ requestLibPath, schemaPath, mockFolder, includeTags, excludeTags, authorization, isTranslateToEnglishTag, priorityRule, reactQueryMode, ...rest }: GenerateServiceProps): Promise<void>;
package/dist/index.js CHANGED
@@ -3,14 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateService = generateService;
4
4
  const tslib_1 = require("tslib");
5
5
  const lodash_1 = require("lodash");
6
+ const config_1 = require("./config");
6
7
  const mockGenarator_1 = require("./generator/mockGenarator");
7
8
  const serviceGenarator_1 = tslib_1.__importDefault(require("./generator/serviceGenarator"));
8
- const type_1 = require("./type");
9
9
  const util_1 = require("./util");
10
10
  tslib_1.__exportStar(require("./generator/patchSchema"), exports);
11
11
  function generateService(_a) {
12
12
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
13
- var { requestLibPath, schemaPath, mockFolder, includeTags, excludeTags, authorization, isTranslateToEnglishTag, priorityRule = type_1.PriorityRule.include } = _a, rest = tslib_1.__rest(_a, ["requestLibPath", "schemaPath", "mockFolder", "includeTags", "excludeTags", "authorization", "isTranslateToEnglishTag", "priorityRule"]);
13
+ var { requestLibPath, schemaPath, mockFolder, includeTags, excludeTags, authorization, isTranslateToEnglishTag, priorityRule = config_1.PriorityRule.include, reactQueryMode = config_1.ReactQueryMode.react } = _a, rest = tslib_1.__rest(_a, ["requestLibPath", "schemaPath", "mockFolder", "includeTags", "excludeTags", "authorization", "isTranslateToEnglishTag", "priorityRule", "reactQueryMode"]);
14
14
  if (!schemaPath) {
15
15
  return;
16
16
  }
@@ -24,11 +24,11 @@ function generateService(_a) {
24
24
  const requestImportStatement = (0, util_1.getImportStatement)(requestLibPath);
25
25
  const serviceGenerator = new serviceGenarator_1.default(Object.assign({ schemaPath, serversPath: './src/apis', requestImportStatement, enableLogging: false, priorityRule, includeTags: includeTags
26
26
  ? (0, lodash_1.map)(includeTags, (item) => typeof item === 'string' ? item.toLowerCase() : item)
27
- : priorityRule === type_1.PriorityRule.include
27
+ : priorityRule === config_1.PriorityRule.include
28
28
  ? [/.*/g]
29
29
  : null, excludeTags: excludeTags
30
30
  ? (0, lodash_1.map)(excludeTags, (item) => typeof item === 'string' ? item.toLowerCase() : item)
31
- : null, requestOptionsType: '{[key: string]: unknown}', namespace: 'API', isGenReactQuery: false, isGenJavaScript: false, isDisplayTypeLabel: false, isGenJsonSchemas: false, nullable: false, isOnlyGenTypeScriptType: false, isCamelCase: true }, rest), openAPI);
31
+ : null, requestOptionsType: '{[key: string]: unknown}', namespace: 'API', isGenReactQuery: false, reactQueryMode, isGenJavaScript: false, isDisplayTypeLabel: false, isGenJsonSchemas: false, nullable: false, isOnlyGenTypeScriptType: false, isCamelCase: true }, rest), openAPI);
32
32
  serviceGenerator.genFile();
33
33
  if (mockFolder) {
34
34
  (0, mockGenarator_1.mockGenerator)({
package/dist/type.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { OpenAPIV3 } from 'openapi-types';
2
+ import { PriorityRule, ReactQueryMode, SchemaObjectFormat, SchemaObjectType } from './config';
2
3
  type Modify<T, R> = Omit<T, keyof R> & R;
3
4
  type ICustomBaseSchemaObject = {
4
5
  type: ISchemaObjectType;
@@ -52,37 +53,7 @@ export type RequestBodyObject = OpenAPIV3.RequestBodyObject;
52
53
  export type ContentObject = {
53
54
  [media: string]: OpenAPIV3.MediaTypeObject;
54
55
  };
55
- export declare enum SchemaObjectFormat {
56
- int32 = "int32",
57
- int64 = "int64",
58
- float = "float",
59
- double = "double",
60
- byte = "byte",
61
- binary = "binary",
62
- date = "date",
63
- dateTime = "date-time",
64
- password = "password",
65
- base64 = "base64"
66
- }
67
56
  export type ISchemaObjectFormat = keyof typeof SchemaObjectFormat;
68
- export declare enum SchemaObjectType {
69
- array = "array",
70
- stringArray = "string[]",
71
- boolean = "boolean",
72
- object = "object",
73
- number = "number",
74
- string = "string",
75
- integer = "integer",
76
- enum = "enum",
77
- null = "null",
78
- union = "union",
79
- file = "file"
80
- }
81
- export declare enum PriorityRule {
82
- include = "include",
83
- exclude = "exclude",
84
- both = "both"
85
- }
86
57
  export type GenerateRegExp = {
87
58
  includeTags: (string | RegExp)[];
88
59
  excludeTags: (string | RegExp)[];
@@ -90,4 +61,6 @@ export type GenerateRegExp = {
90
61
  excludePaths: (string | RegExp)[];
91
62
  };
92
63
  export type ISchemaObjectType = keyof typeof SchemaObjectType;
64
+ export type IReactQueryMode = keyof typeof ReactQueryMode;
65
+ export type IPriorityRule = keyof typeof PriorityRule;
93
66
  export {};
package/dist/type.js CHANGED
@@ -1,36 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PriorityRule = exports.SchemaObjectType = exports.SchemaObjectFormat = void 0;
4
- var SchemaObjectFormat;
5
- (function (SchemaObjectFormat) {
6
- SchemaObjectFormat["int32"] = "int32";
7
- SchemaObjectFormat["int64"] = "int64";
8
- SchemaObjectFormat["float"] = "float";
9
- SchemaObjectFormat["double"] = "double";
10
- SchemaObjectFormat["byte"] = "byte";
11
- SchemaObjectFormat["binary"] = "binary";
12
- SchemaObjectFormat["date"] = "date";
13
- SchemaObjectFormat["dateTime"] = "date-time";
14
- SchemaObjectFormat["password"] = "password";
15
- SchemaObjectFormat["base64"] = "base64";
16
- })(SchemaObjectFormat || (exports.SchemaObjectFormat = SchemaObjectFormat = {}));
17
- var SchemaObjectType;
18
- (function (SchemaObjectType) {
19
- SchemaObjectType["array"] = "array";
20
- SchemaObjectType["stringArray"] = "string[]";
21
- SchemaObjectType["boolean"] = "boolean";
22
- SchemaObjectType["object"] = "object";
23
- SchemaObjectType["number"] = "number";
24
- SchemaObjectType["string"] = "string";
25
- SchemaObjectType["integer"] = "integer";
26
- SchemaObjectType["enum"] = "enum";
27
- SchemaObjectType["null"] = "null";
28
- SchemaObjectType["union"] = "union";
29
- SchemaObjectType["file"] = "file";
30
- })(SchemaObjectType || (exports.SchemaObjectType = SchemaObjectType = {}));
31
- var PriorityRule;
32
- (function (PriorityRule) {
33
- PriorityRule["include"] = "include";
34
- PriorityRule["exclude"] = "exclude";
35
- PriorityRule["both"] = "both";
36
- })(PriorityRule || (exports.PriorityRule = PriorityRule = {}));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "openapi-ts-request",
3
- "version": "1.0.1",
4
- "description": "Swagger2/OpenAPI3/Apifox to TypeScript/JavaScript, request client(support any client), request mock service, enum and enum translation, react-query, type field label, JSON Schemas",
3
+ "version": "1.1.0",
4
+ "description": "Swagger2/OpenAPI3/Apifox to TypeScript/JavaScript, request client(support any client), request mock service, enum and enum translation, react-query/vue-query, type field label, JSON Schemas",
5
5
  "engines": {
6
6
  "node": ">=18.0.0",
7
7
  "pnpm": ">=9"
@@ -25,13 +25,13 @@
25
25
  ],
26
26
  "dependencies": {
27
27
  "@prettier/sync": "^0.5.2",
28
- "@trivago/prettier-plugin-sort-imports": "^4.3.0",
28
+ "@trivago/prettier-plugin-sort-imports": "^5.2.1",
29
29
  "axios": "^1.7.2",
30
30
  "bing-translate-api": "^4.0.2",
31
31
  "chalk": "^4.1.2",
32
32
  "commander": "^12.1.0",
33
33
  "cosmiconfig": "^9.0.0",
34
- "cosmiconfig-typescript-loader": "^5.0.0",
34
+ "cosmiconfig-typescript-loader": "^6.1.0",
35
35
  "glob": "^11.0.0",
36
36
  "js-yaml": "^4.1.0",
37
37
  "lodash": "^4.17.21",
@@ -52,6 +52,7 @@
52
52
  "@commitlint/cli": "^19.2.1",
53
53
  "@commitlint/config-conventional": "^19.2.2",
54
54
  "@tanstack/react-query": "^5.62.10",
55
+ "@tanstack/vue-query": "^5.62.16",
55
56
  "@types/js-yaml": "^4.0.9",
56
57
  "@types/lodash": "^4.17.5",
57
58
  "@types/memoizee": "^0.4.11",
@@ -2,9 +2,9 @@
2
2
  /* eslint-disable */
3
3
  // @ts-ignore
4
4
  {% endif -%}
5
- import { queryOptions, useMutation } from '@tanstack/react-query';
5
+ import { queryOptions, useMutation } from '{{ reactQueryModePackageName }}';
6
6
  {%- if genType === "ts" %}
7
- import type { DefaultError } from '@tanstack/react-query';
7
+ import type { DefaultError } from '{{ reactQueryModePackageName }}';
8
8
  {% endif %}
9
9
 
10
10
  import * as apis from './{{ className }}';