openapi-ts-request 1.8.4 → 1.9.1

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
@@ -1,5 +1,3 @@
1
- <!-- TODO:需要修改文档, 添加参数, 添加apifox的配置支持 -->
2
-
3
1
  ## 介绍
4
2
 
5
3
  [![GitHub Repo stars](https://img.shields.io/github/stars/openapi-ui/openapi-ts-request?style=social)](https://github.com/openapi-ui/openapi-ts-request) [![npm (scoped)](https://img.shields.io/npm/v/openapi-ts-request)](https://www.npmjs.com/package/openapi-ts-request) ![GitHub tag](https://img.shields.io/github/v/tag/openapi-ui/openapi-ts-request?include_prereleases)
@@ -50,8 +48,6 @@ pnpm i openapi-ts-request -D
50
48
  import type { GenerateServiceProps } from 'openapi-ts-request';
51
49
 
52
50
  export default {
53
- // schemaPath: './openapi.json', // 本地openapi文件
54
- // serversPath: './src/apis', // 接口存放路径
55
51
  schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
56
52
  } as GenerateServiceProps;
57
53
  ```
@@ -254,6 +250,7 @@ openapi --i ./spec.json --o ./apis
254
250
  | isOnlyGenTypeScriptType | 否 | boolean | false | 仅生成 typescript 类型 |
255
251
  | isCamelCase | 否 | boolean | true | 小驼峰命名文件和请求函数 |
256
252
  | isSupportParseEnumDesc | 否 | boolean | false | 解析枚举描述生成枚举标签,格式参考:`系统用户角色:User(普通用户)=0,Agent(经纪人)=1,Admin(管理员)=2` |
253
+ | binaryMediaTypes | 否 | string[] | - | 自定义二进制媒体类型列表,默认包含:['application/octet-stream', 'application/pdf', 'image/*', 'video/*', 'audio/*'] |
257
254
  | hook | 否 | [Custom Hook](#Custom-Hook) | - | 自定义 hook |
258
255
 
259
256
  ## 自定义 Hook
@@ -267,6 +264,7 @@ openapi --i ./spec.json --o ./apis
267
264
  | customType | ({<br>schemaObject: SchemaObject \| ReferenceObject,<br>namespace: string,<br>originGetType:(schemaObject: SchemaObject \| ReferenceObject, namespace: string, schemas?: ComponentsObject['schemas']) => string,<br>schemas?: ComponentsObject['schemas'],<br>}) => string | 自定义类型 <br> _返回非字符串将使用默认方法获取type_ |
268
265
  | customFileNames | (<br>operationObject: OperationObject,<br>apiPath: string,<br>apiMethod: string,<br>) => string[] | 自定义生成的请求客户端文件名称,可以返回多个文件名称的数组(表示生成多个文件). <br> _返回为空,则使用默认的方法获取_ |
269
266
  | customTemplates | {<br>[TypescriptFileType.serviceController]?: <T, U>(item: T, context: U) => string;<br>} | 自定义模板,详情请看源码 |
267
+ | customRenderTemplateData | {<br>[TypescriptFileType]?: (list: any[], context: {fileName: string, params: Record<string, unknown>}) => any[]<br>} | 自定义文件生成时的 list 参数处理,支持对不同文件类型进行精细化控制 |
270
268
 
271
269
  ## Apifox-Config
272
270
 
@@ -531,15 +531,75 @@ class ServiceGenerator {
531
531
  .filter((item) => { var _a; return !!((_a = item === null || item === void 0 ? void 0 : item.list) === null || _a === void 0 ? void 0 : _a.length); });
532
532
  }
533
533
  genFileFromTemplate(fileName, type, params) {
534
+ var _a;
534
535
  try {
535
536
  const template = this.getTemplate(type);
537
+ // 应用 customRenderTemplateData hook (如果存在)
538
+ let processedParams = Object.assign({}, params);
539
+ const customListHooks = (_a = this.config.hook) === null || _a === void 0 ? void 0 : _a.customRenderTemplateData;
540
+ if (customListHooks && params.list) {
541
+ try {
542
+ const context = {
543
+ fileName,
544
+ params: processedParams,
545
+ };
546
+ let processedList = params.list;
547
+ // 根据不同的文件类型调用相应的 hook 函数
548
+ switch (type) {
549
+ case config_2.TypescriptFileType.serviceController:
550
+ if (customListHooks.serviceController) {
551
+ processedList = customListHooks.serviceController(params.list, context);
552
+ }
553
+ break;
554
+ case config_2.TypescriptFileType.reactQuery:
555
+ if (customListHooks.reactQuery) {
556
+ processedList = customListHooks.reactQuery(params.list, context);
557
+ }
558
+ break;
559
+ case config_2.TypescriptFileType.interface:
560
+ if (customListHooks.interface) {
561
+ processedList = customListHooks.interface(params.list, context);
562
+ }
563
+ break;
564
+ case config_2.TypescriptFileType.displayEnumLabel:
565
+ if (customListHooks.displayEnumLabel) {
566
+ processedList = customListHooks.displayEnumLabel(params.list, context);
567
+ }
568
+ break;
569
+ case config_2.TypescriptFileType.displayTypeLabel:
570
+ if (customListHooks.displayTypeLabel) {
571
+ processedList = customListHooks.displayTypeLabel(params.list, context);
572
+ }
573
+ break;
574
+ case config_2.TypescriptFileType.schema:
575
+ if (customListHooks.schema) {
576
+ processedList = customListHooks.schema(params.list, context);
577
+ }
578
+ break;
579
+ case config_2.TypescriptFileType.serviceIndex:
580
+ if (customListHooks.serviceIndex) {
581
+ processedList = customListHooks.serviceIndex(params.list, context);
582
+ }
583
+ break;
584
+ }
585
+ if (processedList !== params.list) {
586
+ processedParams = Object.assign(Object.assign({}, processedParams), { list: processedList });
587
+ this.log(`customRenderTemplateData hook applied for ${type}: ${fileName}`);
588
+ }
589
+ }
590
+ catch (error) {
591
+ console.error(`[GenSDK] customRenderTemplateData hook error for ${type}:`, error);
592
+ this.log(`customRenderTemplateData hook failed for ${type}, using original list`);
593
+ // 发生错误时使用原始参数继续执行
594
+ }
595
+ }
536
596
  // 设置输出不转义
537
597
  const env = nunjucks_1.default.configure({
538
598
  autoescape: false,
539
599
  });
540
600
  env.addFilter('capitalizeFirst', util_2.capitalizeFirstLetter);
541
601
  const destPath = (0, path_1.join)(this.config.serversPath, fileName);
542
- const destCode = nunjucks_1.default.renderString(template, Object.assign({ disableTypeCheck: false }, params));
602
+ const destCode = nunjucks_1.default.renderString(template, Object.assign({ disableTypeCheck: false }, processedParams));
543
603
  let mergerProps = {};
544
604
  if ((0, fs_1.existsSync)(destPath)) {
545
605
  mergerProps = {
@@ -674,15 +734,19 @@ class ServiceGenerator {
674
734
  mediaType: '*/*',
675
735
  type: 'unknown',
676
736
  isAnonymous: false,
737
+ responseType: undefined,
677
738
  };
678
739
  if (!response) {
679
740
  return defaultResponse;
680
741
  }
681
742
  const resContent = response.content;
682
743
  const resContentMediaTypes = (0, lodash_1.keys)(resContent);
744
+ // 检测二进制流媒体类型
745
+ const binaryMediaTypes = (0, util_2.getBinaryMediaTypes)(this.config.binaryMediaTypes);
746
+ const binaryMediaType = resContentMediaTypes.find((mediaType) => (0, util_2.isBinaryMediaType)(mediaType, binaryMediaTypes));
683
747
  const mediaType = resContentMediaTypes.includes('application/json')
684
748
  ? 'application/json'
685
- : resContentMediaTypes[0]; // 优先使用 application/json
749
+ : binaryMediaType || resContentMediaTypes[0]; // 优先使用 application/json,然后是二进制类型
686
750
  if (!(0, lodash_1.isObject)(resContent) || !mediaType) {
687
751
  return defaultResponse;
688
752
  }
@@ -692,7 +756,16 @@ class ServiceGenerator {
692
756
  mediaType,
693
757
  type: 'unknown',
694
758
  isAnonymous: false,
759
+ responseType: undefined,
695
760
  };
761
+ // 如果是二进制媒体类型,直接返回二进制类型
762
+ if ((0, util_2.isBinaryMediaType)(mediaType, binaryMediaTypes)) {
763
+ const binaryType = (0, util_2.getBinaryResponseType)();
764
+ responseSchema.type = binaryType;
765
+ // 自动为二进制响应添加 responseType 配置
766
+ responseSchema.responseType = (0, util_2.getAxiosResponseType)(binaryType);
767
+ return responseSchema;
768
+ }
696
769
  if ((0, util_2.isReferenceObject)(schema)) {
697
770
  const refName = (0, util_2.getLastRefName)(schema.$ref);
698
771
  const childrenSchema = components.schemas[refName];
@@ -785,12 +858,19 @@ class ServiceGenerator {
785
858
  }
786
859
  const resContent = response.content;
787
860
  const resContentMediaTypes = (0, lodash_1.keys)(resContent);
861
+ // 检测二进制流媒体类型
862
+ const binaryMediaTypes = (0, util_2.getBinaryMediaTypes)(this.config.binaryMediaTypes);
863
+ const binaryMediaType = resContentMediaTypes.find((mediaType) => (0, util_2.isBinaryMediaType)(mediaType, binaryMediaTypes));
788
864
  const mediaType = resContentMediaTypes.includes('application/json')
789
865
  ? 'application/json'
790
- : resContentMediaTypes[0];
866
+ : binaryMediaType || resContentMediaTypes[0];
791
867
  if (!(0, lodash_1.isObject)(resContent) || !mediaType) {
792
868
  return 'unknown';
793
869
  }
870
+ // 如果是二进制媒体类型,直接返回二进制类型
871
+ if ((0, util_2.isBinaryMediaType)(mediaType, binaryMediaTypes)) {
872
+ return (0, util_2.getBinaryResponseType)();
873
+ }
794
874
  let schema = (resContent[mediaType].schema ||
795
875
  config_2.DEFAULT_SCHEMA);
796
876
  if ((0, util_2.isReferenceObject)(schema)) {
@@ -23,3 +23,30 @@ export declare function isAllNumeric(arr: any): boolean;
23
23
  export declare function isAllNumber(arr: any): boolean;
24
24
  export declare function capitalizeFirstLetter(str: string): string;
25
25
  export declare const parseDescriptionEnum: (description: string) => Map<number, string>;
26
+ /**
27
+ * 获取默认的二进制媒体类型列表
28
+ */
29
+ export declare const getDefaultBinaryMediaTypes: () => string[];
30
+ /**
31
+ * 获取二进制媒体类型列表
32
+ * 支持配置自定义二进制媒体类型
33
+ * @param customBinaryTypes 自定义二进制媒体类型列表
34
+ */
35
+ export declare const getBinaryMediaTypes: (customBinaryTypes?: string[]) => string[];
36
+ /**
37
+ * 检测是否为二进制媒体类型
38
+ * @param mediaType 媒体类型
39
+ * @param binaryMediaTypes 二进制媒体类型列表
40
+ */
41
+ export declare const isBinaryMediaType: (mediaType: string, binaryMediaTypes: string[]) => boolean;
42
+ /**
43
+ * 获取二进制响应类型
44
+ * 默认返回 Blob,这是浏览器环境中最常用的二进制类型
45
+ */
46
+ export declare const getBinaryResponseType: () => string;
47
+ /**
48
+ * 获取 axios responseType 配置
49
+ * 根据二进制响应类型返回对应的 responseType
50
+ * @param binaryType 二进制类型
51
+ */
52
+ export declare const getAxiosResponseType: (binaryType: string) => string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseDescriptionEnum = void 0;
3
+ exports.getAxiosResponseType = exports.getBinaryResponseType = exports.isBinaryMediaType = exports.getBinaryMediaTypes = exports.getDefaultBinaryMediaTypes = exports.parseDescriptionEnum = void 0;
4
4
  exports.stripDot = stripDot;
5
5
  exports.resolveTypeName = resolveTypeName;
6
6
  exports.getRefName = getRefName;
@@ -408,3 +408,72 @@ const parseDescriptionEnum = (description) => {
408
408
  return enumMap;
409
409
  };
410
410
  exports.parseDescriptionEnum = parseDescriptionEnum;
411
+ /**
412
+ * 获取默认的二进制媒体类型列表
413
+ */
414
+ const getDefaultBinaryMediaTypes = () => {
415
+ return [
416
+ 'application/octet-stream',
417
+ 'application/pdf',
418
+ 'application/zip',
419
+ 'application/x-zip-compressed',
420
+ 'image/*',
421
+ 'video/*',
422
+ 'audio/*',
423
+ ];
424
+ };
425
+ exports.getDefaultBinaryMediaTypes = getDefaultBinaryMediaTypes;
426
+ /**
427
+ * 获取二进制媒体类型列表
428
+ * 支持配置自定义二进制媒体类型
429
+ * @param customBinaryTypes 自定义二进制媒体类型列表
430
+ */
431
+ const getBinaryMediaTypes = (customBinaryTypes = []) => {
432
+ const defaultBinaryTypes = (0, exports.getDefaultBinaryMediaTypes)();
433
+ return [...defaultBinaryTypes, ...customBinaryTypes];
434
+ };
435
+ exports.getBinaryMediaTypes = getBinaryMediaTypes;
436
+ /**
437
+ * 检测是否为二进制媒体类型
438
+ * @param mediaType 媒体类型
439
+ * @param binaryMediaTypes 二进制媒体类型列表
440
+ */
441
+ const isBinaryMediaType = (mediaType, binaryMediaTypes) => {
442
+ return binaryMediaTypes.some((type) => {
443
+ if (type.endsWith('/*')) {
444
+ // 处理通配符类型,如 image/*, video/*
445
+ const prefix = type.slice(0, -1);
446
+ return mediaType.startsWith(prefix);
447
+ }
448
+ return mediaType === type;
449
+ });
450
+ };
451
+ exports.isBinaryMediaType = isBinaryMediaType;
452
+ /**
453
+ * 获取二进制响应类型
454
+ * 默认返回 Blob,这是浏览器环境中最常用的二进制类型
455
+ */
456
+ const getBinaryResponseType = () => {
457
+ return 'Blob';
458
+ };
459
+ exports.getBinaryResponseType = getBinaryResponseType;
460
+ /**
461
+ * 获取 axios responseType 配置
462
+ * 根据二进制响应类型返回对应的 responseType
463
+ * @param binaryType 二进制类型
464
+ */
465
+ const getAxiosResponseType = (binaryType) => {
466
+ switch (binaryType.toLowerCase()) {
467
+ case 'blob':
468
+ return 'blob';
469
+ case 'arraybuffer':
470
+ return 'arraybuffer';
471
+ case 'uint8array':
472
+ return 'arraybuffer'; // Uint8Array 需要从 ArrayBuffer 转换
473
+ case 'buffer':
474
+ return 'arraybuffer'; // Node.js Buffer 需要从 ArrayBuffer 转换
475
+ default:
476
+ return 'blob';
477
+ }
478
+ };
479
+ exports.getAxiosResponseType = getAxiosResponseType;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { TypescriptFileType } from './generator/config';
2
- import type { APIDataType, ITypeItem } from './generator/type';
2
+ import type { APIDataType, ControllerType, ISchemaItem, ITypeItem } from './generator/type';
3
3
  import type { ComponentsObject, IPriorityRule, IReactQueryMode, OpenAPIObject, OperationObject, ReferenceObject, SchemaObject } from './type';
4
4
  import { type GetSchemaByApifoxProps } from './type';
5
5
  export * from './generator/patchSchema';
@@ -143,6 +143,11 @@ export type GenerateServiceProps = {
143
143
  * 多网关唯一标识
144
144
  */
145
145
  uniqueKey?: string;
146
+ /**
147
+ * 自定义二进制媒体类型列表
148
+ * 默认包含: ['application/octet-stream', 'application/pdf', 'image/*', 'video/*', 'audio/*']
149
+ */
150
+ binaryMediaTypes?: string[];
146
151
  /**
147
152
  * 自定义 hook
148
153
  */
@@ -217,6 +222,61 @@ export type GenerateServiceProps = {
217
222
  */
218
223
  [TypescriptFileType.displayTypeLabel]?: <T, U>(types: T[], config: U) => ITypeItem[];
219
224
  };
225
+ /**
226
+ * 自定义 genFileFromTemplate 的 list 参数 hook
227
+ * 可以在模板渲染前对 list 参数进行自定义处理
228
+ */
229
+ customRenderTemplateData?: {
230
+ /**
231
+ * 自定义 serviceController 文件的 list 参数
232
+ */
233
+ [TypescriptFileType.serviceController]?: (list: APIDataType[], context: {
234
+ fileName: string;
235
+ params: Record<string, unknown>;
236
+ }) => APIDataType[];
237
+ /**
238
+ * 自定义 interface 文件的 list 参数
239
+ */
240
+ [TypescriptFileType.interface]?: (list: ITypeItem[], context: {
241
+ fileName: string;
242
+ params: Record<string, unknown>;
243
+ }) => ITypeItem[];
244
+ /**
245
+ * 自定义 displayEnumLabel 文件的 list 参数
246
+ */
247
+ [TypescriptFileType.displayEnumLabel]?: (list: ITypeItem[], context: {
248
+ fileName: string;
249
+ params: Record<string, unknown>;
250
+ }) => ITypeItem[];
251
+ /**
252
+ * 自定义 displayTypeLabel 文件的 list 参数
253
+ */
254
+ [TypescriptFileType.displayTypeLabel]?: (list: ITypeItem[], context: {
255
+ fileName: string;
256
+ params: Record<string, unknown>;
257
+ }) => ITypeItem[];
258
+ /**
259
+ * 自定义 schema 文件的 list 参数
260
+ */
261
+ [TypescriptFileType.schema]?: (list: ISchemaItem[], context: {
262
+ fileName: string;
263
+ params: Record<string, unknown>;
264
+ }) => ISchemaItem[];
265
+ /**
266
+ * 自定义 serviceIndex 文件的 list 参数
267
+ */
268
+ [TypescriptFileType.serviceIndex]?: (list: ControllerType[], context: {
269
+ fileName: string;
270
+ params: Record<string, unknown>;
271
+ }) => ControllerType[];
272
+ /**
273
+ * 自定义 reactQuery 文件的 list 参数
274
+ */
275
+ [TypescriptFileType.reactQuery]?: (list: APIDataType[], context: {
276
+ fileName: string;
277
+ params: Record<string, unknown>;
278
+ }) => APIDataType[];
279
+ };
220
280
  };
221
281
  };
222
282
  export declare function generateService({ requestLibPath, schemaPath, mockFolder, includeTags, excludeTags, includePaths, excludePaths, authorization, isTranslateToEnglishTag, priorityRule, timeout, reactQueryMode, apifoxConfig, ...rest }: GenerateServiceProps): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openapi-ts-request",
3
- "version": "1.8.4",
3
+ "version": "1.9.1",
4
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",
@@ -70,7 +70,7 @@
70
70
  "openapi-types": "^12.1.3",
71
71
  "sanitize-filename": "^1.6.3",
72
72
  "ts-node": "^10.9.2",
73
- "typescript": "5.9.2",
73
+ "typescript": "5.9.3",
74
74
  "vitest": "^2.1.9"
75
75
  },
76
76
  "keywords": [
@@ -128,6 +128,9 @@
128
128
  return request{{ ("<" + api.response.type + ">") | safe if genType === "ts" }}('{{ api.path }}', {
129
129
  {% endif -%}
130
130
  method: '{{ api.method | upper }}',
131
+ {%- if api.response.responseType %}
132
+ responseType: '{{ api.response.responseType }}',
133
+ {%- endif %}
131
134
  {%- if api.hasHeader and api.body.mediaType %}
132
135
  headers: {
133
136
  {%- if api.body.mediaType %}