Procházet zdrojové kódy

🎨 优化工具库代码

快乐的梦鱼 před 2 dny
rodič
revize
0388bd0f6d

+ 10 - 7
node_modules/.package-lock.json

@@ -573,15 +573,18 @@
       }
     },
     "node_modules/@imengyu/imengyu-utils": {
-      "version": "0.0.12",
-      "resolved": "https://registry.npmmirror.com/@imengyu/imengyu-utils/-/imengyu-utils-0.0.12.tgz",
-      "integrity": "sha512-+iQJkYNafCNMEfJGGMGEdSnXWkmzb2sL32vHPIxZ/4L7Hhzv9blmuNsEQ5xkqbNQ/n8p38CJjX/rHlsr3GCGsQ==",
-      "license": "MIT"
+      "version": "0.0.13",
+      "resolved": "https://registry.npmjs.org/@imengyu/imengyu-utils/-/imengyu-utils-0.0.13.tgz",
+      "integrity": "sha512-yFcG+d5URj/klasfZdHMtLTpukJVhspt2sqpoUPxErwMJ6l0BxzQHAODz1h+D+d8vJln9x63pdBKUxvubmtx9w==",
+      "license": "MIT",
+      "dependencies": {
+        "@imengyu/js-request-transform": "^0.3.6"
+      }
     },
     "node_modules/@imengyu/js-request-transform": {
-      "version": "0.3.5",
-      "resolved": "https://registry.npmmirror.com/@imengyu/js-request-transform/-/js-request-transform-0.3.5.tgz",
-      "integrity": "sha512-exMBbHxYyuwP6re1lEqq4AY5R0EmvL9jYSNe1DN91GbYCvloGvBP720lJeYOIKopKRki+H84PLLWonxYMzbiDA==",
+      "version": "0.3.6",
+      "resolved": "https://registry.npmjs.org/@imengyu/js-request-transform/-/js-request-transform-0.3.6.tgz",
+      "integrity": "sha512-MeBI2uRWNOwqK0CexCNd831inckQaAp70itpOsN+jneisYOgoV/xTDGnOjj50DJ1NxNyWeja/p8X+EWsz1pLqQ==",
       "license": "MIT",
       "dependencies": {
         "dayjs": "^1.11.7"

+ 11 - 8
package-lock.json

@@ -8,7 +8,7 @@
       "name": "wenlv-huli-showroom",
       "version": "0.0.0",
       "dependencies": {
-        "@imengyu/imengyu-utils": "^0.0.12",
+        "@imengyu/imengyu-utils": "^0.0.13",
         "@imengyu/js-request-transform": "^0.3.5",
         "@imengyu/vue-scroll-rect": "^0.1.7",
         "ant-design-vue": "^4.2.6",
@@ -1030,15 +1030,18 @@
       }
     },
     "node_modules/@imengyu/imengyu-utils": {
-      "version": "0.0.12",
-      "resolved": "https://registry.npmmirror.com/@imengyu/imengyu-utils/-/imengyu-utils-0.0.12.tgz",
-      "integrity": "sha512-+iQJkYNafCNMEfJGGMGEdSnXWkmzb2sL32vHPIxZ/4L7Hhzv9blmuNsEQ5xkqbNQ/n8p38CJjX/rHlsr3GCGsQ==",
-      "license": "MIT"
+      "version": "0.0.13",
+      "resolved": "https://registry.npmjs.org/@imengyu/imengyu-utils/-/imengyu-utils-0.0.13.tgz",
+      "integrity": "sha512-yFcG+d5URj/klasfZdHMtLTpukJVhspt2sqpoUPxErwMJ6l0BxzQHAODz1h+D+d8vJln9x63pdBKUxvubmtx9w==",
+      "license": "MIT",
+      "dependencies": {
+        "@imengyu/js-request-transform": "^0.3.6"
+      }
     },
     "node_modules/@imengyu/js-request-transform": {
-      "version": "0.3.5",
-      "resolved": "https://registry.npmmirror.com/@imengyu/js-request-transform/-/js-request-transform-0.3.5.tgz",
-      "integrity": "sha512-exMBbHxYyuwP6re1lEqq4AY5R0EmvL9jYSNe1DN91GbYCvloGvBP720lJeYOIKopKRki+H84PLLWonxYMzbiDA==",
+      "version": "0.3.6",
+      "resolved": "https://registry.npmjs.org/@imengyu/js-request-transform/-/js-request-transform-0.3.6.tgz",
+      "integrity": "sha512-MeBI2uRWNOwqK0CexCNd831inckQaAp70itpOsN+jneisYOgoV/xTDGnOjj50DJ1NxNyWeja/p8X+EWsz1pLqQ==",
       "license": "MIT",
       "dependencies": {
         "dayjs": "^1.11.7"

+ 1 - 1
package.json

@@ -11,7 +11,7 @@
     "type-check": "vue-tsc --build"
   },
   "dependencies": {
-    "@imengyu/imengyu-utils": "^0.0.12",
+    "@imengyu/imengyu-utils": "^0.0.14",
     "@imengyu/js-request-transform": "^0.3.5",
     "@imengyu/vue-scroll-rect": "^0.1.7",
     "ant-design-vue": "^4.2.6",

+ 2 - 4
src/api/CommonContent.ts

@@ -1,10 +1,8 @@
 import { DataModel, transformArrayDataModel, type NewDataModel } from '@imengyu/js-request-transform';
 import { AppServerRequestModule } from './RequestModules';
-import type { QueryParams } from '../common/request/utils/AllType';
 import ApiCofig from '@/common/config/ApiCofig';
-import { transformSomeToArray } from '@/common/request/utils/Utils';
-import RequestApiConfig from '@/common/request/core/RequestApiConfig';
-import type { RequestOptions } from '@/common/request/core/RequestCore';
+import type { QueryParams } from "@imengyu/imengyu-utils/dist/request";
+import { transformSomeToArray } from '@/api/Utils';
 
 export class GetColumListParams extends DataModel<GetColumListParams> {
   

+ 15 - 12
src/api/RequestModules.ts

@@ -6,17 +6,20 @@
  * * 自定义错误报告处理函数。
  */
 
-import { appendGetUrlParams, appendPostParams, checkIfStringAllEnglish, isNullOrEmpty } from "@/common/request/utils/Utils";
 import AppCofig, { isDev } from "../common/config/AppCofig";
-import RequestApiConfig from "../common/request/core/RequestApiConfig";
-import { RequestApiError, RequestApiResult, type RequestApiErrorType } from "../common/request/core/RequestApiResult";
-import { RequestCoreInstance, RequestOptions } from "../common/request/core/RequestCore";
-import { defaultResponseDataGetErrorInfo, defaultResponseDataHandlerCatch } from "../common/request/core/RequestHandler";
-import type { DataModel, NewDataModel } from "@imengyu/js-request-transform";
+import { RequestSharedData } from "@/api/RequestSharedData";
 import ApiCofig from "@/common/config/ApiCofig";
-import implementer from "@/common/request/implementer/WebFetch";
+import implementer from "@imengyu/imengyu-utils/dist/request/implementer/WebFetch";
+import { 
+  RequestApiConfig,
+  RequestApiError, RequestApiResult, type RequestApiErrorType, 
+  RequestCoreInstance, RequestOptions, 
+  defaultResponseDataGetErrorInfo, defaultResponseDataHandlerCatch, 
+  RequestResponse} from "@imengyu/imengyu-utils/dist/request";
+import { appendGetUrlParams, appendPostParams } from "@imengyu/imengyu-utils/dist/request/utils/Utils";
+import type { DataModel, NewDataModel } from "@imengyu/js-request-transform";
 import { Modal } from "ant-design-vue";
-import { RequestSharedData } from "@/common/request/core/RequestSharedData";
+import { StringUtils } from "@imengyu/imengyu-utils";
 
 /**
  * 不报告错误的 code
@@ -39,7 +42,7 @@ function requestInceptor(url: string, req: RequestOptions) {
     
   const token = RequestSharedData.get('token') ?? '';
   const userId = RequestSharedData.get('userId') ?? '';
-  if (isNullOrEmpty((req.header as any).token as string)) {
+  if (StringUtils.isNullOrEmpty((req.header as any).token as string)) {
     req.header['token'] = token
     req.header['__token__'] = token;
   }
@@ -59,7 +62,7 @@ function requestInceptor(url: string, req: RequestOptions) {
   return { newUrl: url, newReq: req };
 }
 //响应数据处理函数
-function responseDataHandler<T extends DataModel>(response: Response, req: RequestOptions, resultModelClass: NewDataModel|undefined, instance: RequestCoreInstance<T>, apiName: string | undefined): Promise<RequestApiResult<T>> {
+function responseDataHandler<T extends DataModel>(response: RequestResponse, req: RequestOptions, resultModelClass: NewDataModel|undefined, instance: RequestCoreInstance<T>, apiName: string | undefined): Promise<RequestApiResult<T>> {
   return new Promise<RequestApiResult<T>>((resolve, reject) => {
     const method = req.method || 'GET';
     response.json().then((json) => {
@@ -122,7 +125,7 @@ function responseDataHandler<T extends DataModel>(response: Response, req: Reque
         if (typeof json.msg === 'string') 
           errString += json.msg;
 
-        if (checkIfStringAllEnglish(errString))
+        if (StringUtils.isStringAllEnglish(errString))
           errString = '服务器返回:' + errString;
 
         //错误处理
@@ -222,7 +225,7 @@ export class HuliRequestModule<T extends DataModel> extends RequestCoreInstance<
 export class AppServerRequestModule<T extends DataModel> extends RequestCoreInstance<T> {
   constructor() {
     super(implementer);
-    this.config.baseUrl = RequestApiConfig.getConfig().BaseUrl;
+    this.config.baseUrl = ApiCofig.serverProd;
     this.config.errCodes = []; //
     this.config.requestInceptor = requestInceptor;
     this.config.responseDataHandler = responseDataHandler;

src/common/request/core/RequestSharedData.ts → src/api/RequestSharedData.ts


+ 15 - 0
src/api/Utils.ts

@@ -0,0 +1,15 @@
+export function transformSomeToArray(source: any) {
+  if (typeof source === 'string') 
+    return source.split(','); 
+  if (typeof source === 'object') {
+    if (source instanceof Array)
+      return source; 
+    else {
+      const arr = [];
+      for (const key in source)
+        arr.push(source[key]);
+      return arr;
+    }
+  }
+  return source;
+}

+ 0 - 59
src/common/request/core/RequestApiConfig.ts

@@ -1,59 +0,0 @@
-/**
- * 请求的默认配置
- *
- * 说明:
- *  此处提供的是请求中的默认配置。
- *
- * Author: imengyu
- * Date: 2022/03/25
- *
- * Copyright (c) 2021 imengyu.top. Licensed under the MIT License.
- * See License.txt in the project root for license information.
- */
-
-import ApiCofig from "@/common/config/ApiCofig";
-import { isDev } from "@/common/config/AppCofig";
-import type { KeyValue } from "@imengyu/js-request-transform/dist/DataUtils";
-
-interface ApiConfigInterface {
-  /**
-   * 默认转换日期的格式
-   */
-  DataDateFormat: string,
-  /**
-  * 所有请求默认携带的header
-  */
-  DefaultHeader: KeyValue,
-  /**
-  * 是否在在控制台上打印出请求信息
-  */
-  EnableApiRequestLog: boolean,
-  /**
-  * 是否在每一个请求都在控制台上打印出休息数据
-  */
-  EnableApiDataLog: boolean,
-  /**
-   * 基础请求地址
-   */
-  BaseUrl: string;
-}
-
-const defaultConfig = {
-  BaseUrl: isDev ? ApiCofig.serverDev : ApiCofig.serverProd,
-  DataDateFormat: 'YYYY-MM-DD HH:mm:ss',
-  DefaultHeader: {},
-  EnableApiRequestLog: true,
-  EnableApiDataLog: false,
-} as ApiConfigInterface;
-
-let config = defaultConfig;
-
-/**
- * 请求中的默认配置
- */
-const RequestApiConfig = {
-  getConfig() : ApiConfigInterface { return config; },
-  setConfig(newConfig: ApiConfigInterface): void { config = newConfig; },
-};
-
-export default RequestApiConfig;

+ 0 - 172
src/common/request/core/RequestApiResult.ts

@@ -1,172 +0,0 @@
-/**
- * API 返回结构体定义
- *
- * 功能介绍:
- *    这里定义了API返回数据的基本结构体,分为正常结果和错误结果。
- *
- * Author: imengyu
- * Date: 2020/09/28
- *
- * Copyright (c) 2021 imengyu.top. Licensed under the MIT License.
- * See License.txt in the project root for license information.
- */
-
-import { DataModel, type NewDataModel } from "@imengyu/js-request-transform";
-import type { KeyValue } from "@imengyu/js-request-transform/dist/DataUtils";
-
-/**
- * API 的返回结构体
- */
-export class RequestApiResult<T extends DataModel> {
-  public code = 0;
-  public message = '';
-  public data: T|KeyValue|null = null;
-  /**
-   * 无类型数据
-   */
-  public data2: any = null;
-  public raw: any = null;
-
-  public constructor(c: NewDataModel|null, code? : number, message? : string, data?: Record<string, unknown>|null, rawData?: Record<string, unknown>|null) {
-    if (typeof code !== 'undefined')
-      this.code = code;
-    if (typeof message !== 'undefined')
-      this.message = message;
-
-    //转换数据
-    if (typeof data !== 'undefined' && c)
-      this.data = new c().fromServerSide(data as KeyValue) as T;//转换data
-    else if (typeof rawData !== 'undefined' && c)
-      this.data = new c().fromServerSide(rawData as KeyValue) as T;//如果data为空则转换rawData
-    else
-      this.data = data as KeyValue as T; //原始数据
-    if (typeof rawData !== 'undefined')
-      this.raw = rawData;
-    else
-      this.raw = this.data;
-    this.data2 = this.data;
-  }
-
-  /**
-   * 使用另一个数据实例克隆当前结果
-   * @param model 另一个数据
-   * @returns
-   */
-  public cloneWithOtherModel<U extends DataModel>(model: U) : RequestApiResult<U> {
-    return new RequestApiResult(
-      null,
-      this.code,
-      this.message,
-      model.keyValue(),
-      this.raw
-    );
-  }
-  /**
-   * 转为纯JSON格式
-   * @returns
-   */
-  public keyValueData() : KeyValue {
-    return (this.data instanceof DataModel ? this.data?.keyValue() : this.data) || {};
-  }
-  /**
-   * 转为字符串表达形式
-   * @returns
-   */
-  public toString() : string {
-    return `${this.code} ${this.message} data: ${JSON.stringify(this.data)} raw: ` + JSON.stringify(this.raw);
-  }
-}
-
-/**
- * 指示这个错误发生的类型
- */
-export type RequestApiErrorType = 'networkError'|'statusError'|'serverError'|'businessError'|'scriptError'|'unknow';
-
-/**
- * API 的错误信息
- */
-export class RequestApiError {
-
-  /**
-   * 本次请求错误的 API 名字
-   */
-  public apiName = '';
-  /**
-   * 本次请求错误的 API URL
-   */
-  public apiUrl = '';
-  /**
-   * 指示这个错误发生的类型
-   * * networkError:网络连接错误
-   * * statusError:状态错误(返回了400-499错误状态码)
-   * * serverError:服务器错误(返回了500-599错误状态码)
-   * * businessError:业务错误(状态码200,但是自定义判断条件失败)
-   * * scriptError:脚本错误(通常是代码异常被catch)
-   */
-  public errorType : RequestApiErrorType = 'unknow';
-  /**
-   * 错误信息
-   */
-  public errorMessage: string;
-  /**
-   * code的错误信息
-   */
-  public errorCodeMessage: string;
-  /**
-   * 错误代号
-   */
-  public code = 0;
-  /**
-   * 本次请求的返回数据
-   */
-  public data: KeyValue|null = null;
-  /**
-   * 本次请求的原始返回数据
-   */
-  public rawData: KeyValue|null = null;
-  /**
-   * 本次请求的原始参数
-   */
-  public rawRequest: RequestInit|null = null;
-
-  public constructor(
-    errorType: RequestApiErrorType,
-    errorMessage = '',
-    errorCodeMessage = '',
-    code = 0,
-    data: KeyValue|null = null,
-    rawData: unknown|null = null,
-    rawRequest: RequestInit|null = null,
-    apiName = '',
-    apiUrl = ''
-  ) {
-    this.errorType = errorType;
-    this.errorMessage = errorMessage;
-    this.errorCodeMessage = errorCodeMessage;
-    this.code = code;
-    this.data = data;
-    this.apiName = apiName;
-    this.apiUrl = apiUrl;
-    this.rawData = rawData as KeyValue;
-    this.rawRequest = rawRequest as KeyValue;
-  }
-
-  /**
-   * 转为详情格式
-   * @returns
-   */
-  public toStringDetail() {
-    return `请求${this.apiName}错误 ${this.errorMessage} (${this.errorType}) ${this.code}(${this.errorCodeMessage})\n` +
-      `url: ${this.apiUrl}\n` +
-      `data: ${JSON.stringify(this.data)}\n` +
-      `rawData: ${JSON.stringify(this.rawData)}\n` +
-      `rawRequest: ${JSON.stringify(this.rawRequest)}\n`;
-  }
-  /**
-   * 转为字符串表达形式
-   * @returns
-   */
-  public toString(): string {
-    return this.errorMessage;
-  }
-}

+ 0 - 398
src/common/request/core/RequestCore.ts

@@ -1,398 +0,0 @@
-import RequestApiConfig from './RequestApiConfig';
-import { DataModel, type NewDataModel } from '@imengyu/js-request-transform';
-import { isNullOrEmpty, stringHashCode } from '../utils/Utils';
-import { RequestApiError, RequestApiResult } from './RequestApiResult';
-import { defaultResponseDataHandler, defaultResponseErrorHandler } from './RequestHandler';
-import type { HeaderType, QueryParams, TypeSaveable } from '../utils/AllType';
-import type { KeyValue } from '@imengyu/js-request-transform/dist/DataUtils';
-import type { RequestImplementer } from './RequestImplementer';
-
-/**
- * API 请求核心
- *
- * 功能介绍:
- *    本类是对 fetch 的封装,提供了基本的请求功能。
- *
- * Author: imengyu
- * Date: 2022/03/28
- *
- * Copyright (c) 2021 imengyu.top. Licensed under the MIT License.
- * See License.txt in the project root for license information.
- */
-
-/**
- * 请求配置体
- */
-export interface RequestCoreConfig<T extends DataModel> {
-  /**
-   * 基础URL
-   */
-  baseUrl: string;
-  /**
-   * 错误代码字符串数据
-   */
-  errCodes: { [index: number]: string };
-  /**
-   * 默认携带header
-   */
-  defaultHeader: HeaderType,
-  /**
-   * 超时时间 ms
-   */
-  timeout: number,
-  /**
-   * 请求拦截
-   */
-  requestInceptor?: (url: string, req: RequestOptions) => { newUrl: string, newReq: RequestOptions };
-  /**
-   * 响应拦截
-   */
-  responseInceptor?: (response: Response) => Response;
-  /**
-   * 错误报告拦截。如果返回true,则不进行错误报告
-   */
-  responseErrReoprtInceptor?: (instance: RequestCoreInstance<T>, err: RequestApiError) => boolean;
-  /**
-   * 错误报告函数
-   */
-  reportError?: (instance: RequestCoreInstance<T>, err: RequestApiError|Error) => void;
-
-  /**
-   * 自定义数据处理函数
-   */
-  responseDataHandler?: (response: Response, req: RequestOptions, resultModelClass: NewDataModel|undefined, instance: RequestCoreInstance<T>, apiName: string|undefined) => Promise<RequestApiResult<T>>;
-  /**
-   * 自定义错误处理函数
-   */
-  responseErrorHandler?: (err: Error, instance: RequestCoreInstance<T>, apiName: string|undefined) => RequestApiError;
-  /**
-   * 类自定义创建函数
-   */
-  modelClassCreator: ModelClassCreatorDefine<T>|null;
-}
-
-type ModelClassCreatorDefine<T> = (new () => T);
-
-export interface RequestCacheConfig {
-  /**
-   * 缓存保存时间,毫秒。超过时间后再请求时会发请求
-   */
-  cacheTime: number,
-  /**
-   * 是否启用缓存
-   */
-  cacheEnable: boolean,
-}
-
-export interface RequestCacheStorage {
-  time: number,
-  data: TypeSaveable
-}
-
-export class RequestOptions {
-  /**
-   * 请求的参数
-   */
-  data?: string | object | ArrayBuffer | FormData;
-  /**
-  * 设置请求的 header,header 中不能设置 Referer。
-  */
-  header?: any;
-  /**
-  * 默认为 GET
-  * 可以是:OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
-  */
-  method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
-  /**
-  * 超时时间
-  */
-  timeout?: number;
-  /**
-  * 如果设为json,会尝试对返回的数据做一次 JSON.parse
-  */
-  dataType?: string;
-  /**
-  * 设置响应的数据类型。合法值:text、arraybuffer
-  */
-  responseType?: string;
-  /**
-  * 验证 ssl 证书
-  */
-  sslVerify?: boolean;
-  /**
-  * 跨域请求时是否携带凭证
-  */
-  withCredentials?: boolean;
-  /**
-  * DNS解析时优先使用 ipv4
-  */
-  firstIpv4?: boolean;
-}
-/**
- * API 请求核心实例类,本类是对 fetch 的封装,提供了基本的请求功能。
- */
-export class RequestCoreInstance<T extends DataModel> {
-
-  constructor(implementer: RequestImplementer) {
-    this.implementer = implementer;
-  }
-
-  /**
-   * 当前请求实例的请求配置项
-   */
-  config : RequestCoreConfig<T> = {
-    baseUrl: '',
-    errCodes: {},
-    timeout: 10000,
-    defaultHeader: RequestApiConfig.getConfig().DefaultHeader as HeaderType,
-    modelClassCreator: null,
-    responseDataHandler: defaultResponseDataHandler,
-    responseErrorHandler: defaultResponseErrorHandler,
-  };
-
-  /**
-   * 请求实现类
-   */
-  implementer: RequestImplementer;
-
-  /**
-   * 检查是否需要报告错误
-   */
-  checkShouldReportError(err: RequestApiError) {
-    if (typeof this.config.responseErrReoprtInceptor === 'function')
-      return this.config.responseErrReoprtInceptor(this, err) !== true;
-    return true;
-  }
-  /**
-   * 报告错误
-   * @param err 错误
-   */
-  reportError(err: RequestApiError|Error) {
-    if (this.checkShouldReportError(err as RequestApiError)) {
-      if (typeof this.config.reportError === 'function')
-        this.config.reportError(this, err);
-    }
-  }
-  /**
-   * 在配置中查找错误代码的说明文字
-   * @param code 错误代码
-   * @returns 说明文字,如果找不到,返回 undefined
-   */
-  findErrCode(code: number) : string|undefined {
-    return this.config.errCodes[code];
-  }
-
-  /**
-   * 合并URL
-   */
-  makeUrl(url: string, querys?: QueryParams) {
-    let finalUrl = '';
-    if (url.indexOf('http') === 0)
-      finalUrl = url; //绝对地址
-    else
-      finalUrl = this.config.baseUrl + url;
-    //处理query
-    if (querys) {
-      let i = finalUrl.indexOf('?') > 0 ? 1 : 0;
-      for (const key in querys) {
-        if (typeof querys[key] === 'undefined' || querys[key] === null)
-          continue;
-        finalUrl += i === 0 ? '?' : '&';
-        if (typeof querys[key] === 'object')
-          finalUrl += `${key}=` + encodeURIComponent(JSON.stringify(querys[key]));
-        else
-          finalUrl += `${key}=` + '' + querys[key];
-        i++;
-      }
-    }
-    return finalUrl;
-  }
-  //合并默认Header参数
-  private mergerDefaultHeader(header: Record<string, unknown>) {
-    const myHeaders = {} as Record<string, unknown>;
-    for (const key in this.config.defaultHeader)
-      myHeaders[key] = this.config.defaultHeader[key];
-    if (header) {
-      for (const key in header) 
-        myHeaders[key] = header[key];
-    }
-    return myHeaders;
-  }
-  /**
-   * 合并两个Header参数
-   * @param header 合并目标
-   * @param newHeader 新的Header
-   * @returns 合并后的Header
-   */
-  mergerHeaders(header: Record<string, unknown>, newHeader: Record<string, unknown>) {
-    if (!newHeader)
-      return header;
-    if (!header)
-      return newHeader;
-    for (const key in newHeader)
-      header[key] = newHeader[key];
-    return header;
-  }
-
-  //检查缓存参数
-  private checkCacheTime(cache?: RequestCacheConfig) {
-    return cache && cache.cacheEnable && cache.cacheTime || 0;
-  }
-  //请求缓存处理
-  private solveCache(url: string, req: RequestOptions, cache: RequestCacheConfig|undefined, callback: (cacheTime: number, cacheKey: string, res: TypeSaveable) => void) {
-    const cacheTime = req.method === 'GET' ? this.checkCacheTime(cache) : 0;
-    let requestHash = '';
-    if (cacheTime > 0) {
-      requestHash = "RequestCache" + stringHashCode(url + req.method);
-      //获取数据
-      this.implementer.getCache(requestHash).then((cacheData) => {
-        if (!cacheData) {
-          callback(cacheTime, requestHash, null);
-          return;
-        }
-        //没有过期
-        if (cacheData.time < new Date().getTime()) {
-          callback(cacheTime, requestHash, cacheData.time);
-          return;
-        }
-        callback(cacheTime, requestHash, null);
-      }).catch(() => {
-        callback(cacheTime, requestHash, null);
-      }); 
-    } else
-      callback(cacheTime, requestHash, null);
-  }
-
-  /**
-   * 通用的请求包装方法
-   * @param url 请求URL
-   * @param req 请求参数
-   * @param apiName 名称,用于日志和调试
-   * @returns 返回 Promise
-   */
-  request(url: string, req: RequestOptions,  apiName: string, modelClassCreator: NewDataModel|undefined, cache?: RequestCacheConfig) : Promise<RequestApiResult<T>> {
-    return new Promise<RequestApiResult<T>>((resolve, reject) => {
-      //附加请求头
-      req.header = this.mergerDefaultHeader(req.header);
-      
-      //拦截器
-      if (this.config.requestInceptor) {
-        const { newUrl, newReq } = this.config.requestInceptor(url, req);
-        url = newUrl;
-        req = newReq;
-      }
-      if (req.data instanceof FormData) {
-        req.header['Content-Type'] = 'multipart/form-data';
-      } else if (typeof req.data === 'object' || req.data === undefined) {
-        req.header['Content-Type'] = 'application/json';
-      }
-
-      if (RequestApiConfig.getConfig().EnableApiRequestLog)
-        console.log(`[API Debugger] Q > ${apiName} [${req.method || 'GET'}] ` + url, req.data);
-
-      //缓存处理
-      this.solveCache(url, req, cache, (cacheTime, cacheKey, cacheRes) => {
-
-        //有缓存数据,则直接返回
-        if (cacheRes) {
-          if (RequestApiConfig.getConfig().EnableApiRequestLog)
-            console.log(`[API Debugger] C > ${apiName} (${cacheKey}/${cacheTime})`, ( RequestApiConfig.getConfig().EnableApiDataLog ? cacheRes.toString() : ''));
-          resolve(cacheRes as unknown as RequestApiResult<T>);
-          return;
-        }
-
-        //发送请求并且处理响应数据
-        this.requestAndResponse(url, req, apiName, modelClassCreator, (result) => {
-          //保存缓存
-          if (cacheTime > 0) {
-            this.implementer.setCache(cacheKey, {
-              time: new Date().getTime() + cacheTime,
-              data: result as unknown as TypeSaveable,
-            });
-          }
-        }).then((d) => {
-          resolve(d);
-        }).catch((e) => {
-          reject(e);
-        });
-      });
-    });
-  }
-
-  //发送请求并且处理
-  private requestAndResponse(url: string, req: RequestOptions, apiName: string, resultModelClass: NewDataModel|undefined, saveCache?: (result: unknown) => void) {
-    return new Promise<RequestApiResult<T>>((resolve, reject) => {
-      //发起请求
-      this.implementer.doRequest(url, req, this.config.timeout).then((res) => {
-        //响应拦截
-        if (this.config.responseInceptor)
-          res = this.config.responseInceptor(res);
-
-        if (this.config.responseDataHandler) {
-          //处理数据
-          this.config.responseDataHandler(res, req, resultModelClass, this, apiName).then((result) => {
-            //尝试保存缓存
-            saveCache && saveCache(result);
-            //处理数据
-            try {
-              if (RequestApiConfig.getConfig().EnableApiRequestLog)
-                console.log(`[API Debugger] R > ${apiName} (${res.status}/${result.code})`);
-              //返回
-              resolve(result);
-            } catch (e) {
-              //捕获处理代码的异常
-              console.error('[API Debugger] E > Catch exception in promise : ' + e + ((e as Error).stack ? ('\n' + (e as Error).stack) : ''));
-              reject(new RequestApiError('scriptError', '代码异常,请检查:' + e, '脚本异常', -1, null, e as unknown as KeyValue, req, apiName));
-            }
-          }).catch((e) => {
-            reject(e);
-          });
-        }
-        else
-          reject(new RequestApiError('scriptError', 'This RequestCoreInstance is not configured with responsedatahandler and cannot convert data! ', '脚本异常', -1, null, null, req, apiName));
-      }).catch((err) => {
-        reject(this.config.responseErrorHandler ? this.config.responseErrorHandler(err, this, apiName) : err);
-      });
-    });
-  }
-
-  /**
-   * GET 请求
-   * @param url 请求URL
-   * @param querys 请求URL参数
-   * @param cache 缓存参数
-   */
-  get(url: string, apiName: string, querys?: QueryParams, modelClassCreator?: NewDataModel, cache?: RequestCacheConfig, headers?: KeyValue) {
-    return this.request(this.makeUrl(url, querys), { method: 'GET', header: headers }, apiName, modelClassCreator, cache);
-  }
-  /**
-   * POST 请求
-   * @param url 请求URL
-   * @param data 请求Body参数
-   * @param querys 请求URL参数
-   * @param cache 缓存参数
-   */
-  post(url: string, data: KeyValue|FormData, apiName: string, querys?: QueryParams, modelClassCreator?: NewDataModel, cache?: RequestCacheConfig, headers?: KeyValue) {
-    return this.request(this.makeUrl(url, querys), { method: 'POST', data, header: headers }, apiName, modelClassCreator, cache);
-  }
-  /**
-   * PUT 请求
-   * @param url 请求URL
-   * @param data 请求Body参数
-   * @param querys 请求URL参数
-   * @param cache 缓存参数
-   */
-  put(url: string, data: KeyValue, apiName: string,querys?: QueryParams,  modelClassCreator?: NewDataModel, cache?: RequestCacheConfig, headers?: KeyValue) {
-    return this.request(this.makeUrl(url, querys), { method: 'PUT', data, header: headers }, apiName, modelClassCreator, cache);
-  }
-  /**
-   * DELETE 请求
-   * @param url 请求URL
-   * @param data 请求Body参数
-   * @param querys 请求URL参数
-   * @param cache 缓存参数
-   */
-  delete(url: string, data: KeyValue, apiName: string, querys?: QueryParams, modelClassCreator?: NewDataModel, cache?: RequestCacheConfig, headers?: KeyValue) {
-    return this.request(this.makeUrl(url, querys), { method: 'DELETE', data, header: headers }, apiName, modelClassCreator, cache);
-  }
-}

+ 0 - 130
src/common/request/core/RequestHandler.ts

@@ -1,130 +0,0 @@
-import ApiConfig from "./RequestApiConfig";
-import { DataModel, type NewDataModel } from "@imengyu/js-request-transform";
-import { RequestApiError, type RequestApiErrorType, RequestApiResult } from "./RequestApiResult";
-import { RequestCoreInstance, RequestOptions } from "./RequestCore";
-
-/**
- * 请求错误与数据处理函数
- *
- * 这里写的是请求中的 数据处理函数 与 错误默认处理函数。
- *
- * 业务相关的自定义数据处理函数,请单独在RequestModules中写明。
- *
- * Author: imengyu
- * Date: 2022/03/28
- *
- * Copyright (c) 2021 imengyu.top. Licensed under the MIT License.
- * See License.txt in the project root for license information.
- */
-
-//默认的请求数据处理函数
-export function defaultResponseDataHandler<T extends DataModel>(response: Response, req: RequestOptions, resultModelClass: NewDataModel|undefined, instance: RequestCoreInstance<T>, apiName: string|undefined) : Promise<RequestApiResult<T>> {
-  return new Promise<RequestApiResult<T>>((resolve, reject) => {
-    const method = req.method || 'GET';
-    response.json().then((json) => {
-      //情况1,有返回数据
-      if (response.ok) {
-        if (ApiConfig.getConfig().EnableApiRequestLog)
-          console.log(`[API Debugger] Request [${method}] ` + response.url + ' success (' + response.status + ') ' + (ApiConfig.getConfig().EnableApiDataLog ? JSON.stringify(json) : ''));
-
-        //情况1-1,请求成功,状态码200-299
-        resolve(new RequestApiResult(resultModelClass ?? instance.config.modelClassCreator, response.status, json.message, json.data, json));
-      } else {
-        if (ApiConfig.getConfig().EnableApiRequestLog)
-          console.log(`[API Debugger] Request [${method}] ${response.url} Got error from server : ` + json.message + ' (' + json.code + ') ' + (ApiConfig.getConfig().EnableApiDataLog ? JSON.stringify(json) : ''));
-
-        //情况1-2,请求失败,状态码>299
-        const err = new RequestApiError('statusError', json.message, '状态码异常', json.code || response.status, json.data, json, req, apiName, response.url);
-
-        //错误报告
-        if (instance.checkShouldReportError(err))
-          instance.reportError(err);
-
-        reject(err);
-      }
-    }).catch((err) => {
-      //错误统一处理
-      defaultResponseDataHandlerCatch(method, req, response, null, err, apiName, response.url, reject, instance);
-    });
-  });
-}
-export function defaultResponseDataGetErrorInfo(response: Response, err: any) {
-  let errString = (response.status > 299) ? ('返回了状态码' + response.status + '。\n') : '';
-  let errType : RequestApiErrorType = 'statusError';
-  let errCodeStr = '状态码:' + response.status;
-  if (err instanceof Error && response.status < 299) {
-    errString = '代码错误: ' + err.message;
-    errType = 'scriptError';
-  } else {
-    if (('' + err).indexOf('JSON Parse error') >= 0)
-      errString += '处理JSON结构失败,可能后端没有返回正确的JSON格式。\n';
-
-    //情况2,没有返回数据
-    //错误状态码的处理
-    switch (response.status) {
-      case 400:
-        errCodeStr = '错误的请求';
-        errString += errCodeStr + ' \n[提示:请检查传入参数是否正确]';
-        errType = 'statusError';
-        break;
-      case 401:
-        errCodeStr = '未登录。可能登录已经过期,请重新登录';
-        errString += errCodeStr;
-        errType = 'statusError';
-        break;
-      case 405:
-        errCodeStr = 'HTTP方法不被允许';
-        errString += errCodeStr + ' \n[提示:这可能是调用接口是不正确造成的]';
-        errType = 'statusError';
-        break;
-      case 404:
-        errCodeStr = '返回404未找到';
-        errString += errCodeStr + ' \n[提示:后端检查下到底有没有提供这个API?]';
-        errType = 'statusError';
-        break;
-      case 500:
-        errCodeStr = '服务异常,请稍后重试';
-        errString += errCodeStr + ' \n[故障提示:这可能是后端服务出现了异常]';
-        errType = 'serverError';
-        break;
-      case 502:
-        errCodeStr = '无效网关,请反馈此错误';
-        errString += errCodeStr + ' \n[故障提示:请检查服务器与软件状态]';
-        errType = 'serverError';
-        break;
-      case 503:
-        errCodeStr = '服务暂时不可用';
-        errString += errCodeStr + ' \n[故障提示:请检查服务器状态]';
-        errType = 'serverError';
-        break;
-    }
-  }
-
-  return {errString, errType, errCodeStr};
-}
-//默认的请求数据处理函数
-export function defaultResponseDataHandlerCatch<T extends DataModel>(method: string, req: RequestOptions, response: Response, data: any, err: any, apiName: string|undefined, apiUrl: string, reject: (reason?: any) => void, instance: RequestCoreInstance<T>) {
-  if (ApiConfig.getConfig().EnableApiRequestLog) {
-    console.log(`[API Debugger] E > ${apiName} ` + err + ' status: ' + response.status);
-    if (err instanceof Error)
-      console.log(err.stack);
-  }
-
-  
-  const {errString, errType, errCodeStr} = defaultResponseDataGetErrorInfo(response, err);
-  const errObj = new RequestApiError(errType, errString, errCodeStr, response.status, null, data, req, apiName, apiUrl);
-
-  //错误报告
-  if (instance.checkShouldReportError(errObj))
-    instance.reportError(errObj);
-  reject(errObj);
-}
-
-//默认的请求错误处理函数
-export function defaultResponseErrorHandler(err: Error) : RequestApiError {
-  if (err instanceof Error)
-    console.error('[API Debugger] Error : ' + err + (err.stack ? ('\n' + err.stack) : ''));
-  else
-    console.error('[API Debugger] Error : ' + JSON.stringify(err));
-  return new RequestApiError('unknow', '' + JSON.stringify(err));
-}

+ 0 - 7
src/common/request/core/RequestImplementer.ts

@@ -1,7 +0,0 @@
-import type { RequestCacheStorage, RequestOptions } from "./RequestCore";
-
-export interface RequestImplementer {
-  getCache(key: string): Promise<RequestCacheStorage|null>;
-  setCache(key: string, value: RequestCacheStorage|null): Promise<void>;
-  doRequest(url: string, init?: RequestOptions, timeout?: number): Promise<Response>;
-}

+ 0 - 103
src/common/request/implementer/Uniapp.ts

@@ -1,103 +0,0 @@
-import type { RequestCacheStorage, RequestOptions } from "../core/RequestCore";
-import type { RequestImplementer } from "../core/RequestImplementer";
-import { isNullOrEmpty } from "../utils/Utils";
-
-export class Response {
-  public constructor(url: string, data: unknown, options: {
-    headers: Record<string, unknown>,
-    status: number,
-  }, errMsg: string) {
-    this.errMsg = errMsg;
-    this.data = data;
-    this.url = url;
-    this.status = options.status;
-    this.headers = options.headers;
-    this.ok = options.status >= 200 && options.status <= 399;
-  }
-
-  headers: Record<string, unknown>;
-  ok: boolean;
-  status: number;
-  errMsg: string;
-  url: string;
-  data: unknown;
-
-  json() : Promise<any> {
-    return new Promise<any>((resolve, reject) => {
-      if (typeof this.data === 'undefined' || isNullOrEmpty(this.data)) {
-        resolve({});
-        return;
-      }
-      if (typeof this.data === 'object') {
-        resolve(this.data);
-        return;
-      }
-      let data = null;
-      
-      if (typeof this.data === 'string') {
-        try {
-          data = JSON.parse(this.data);
-        } catch(e) {
-          console.log('json error: ' + e,  this.data);
-          
-          reject(e);
-        }
-      } else {
-        data = this.data;
-      }
-
-      resolve(data);
-    })
-  }
-}
-
-const uniappImplementer : RequestImplementer = {
-  getCache: function (key: string) {
-    return new Promise<RequestCacheStorage|null>((resolve, reject) => {
-      uni.getStorage({
-        key: key,
-        success: (res) => {
-          resolve(res.data ? JSON.parse(res.data) as RequestCacheStorage : null);
-        },
-        fail: (res) => {
-          resolve(null);
-        }
-      });
-    });
-  },
-  setCache: async function (key: string, value: RequestCacheStorage|null) {
-    return new Promise<void>((resolve, reject) => {
-      uni.setStorage({
-        key: key,
-        data: JSON.stringify(value),
-        success: (res) => {
-          resolve();
-        },
-        fail: (res) => {
-          resolve();
-        }
-      });
-    });
-  },
-  doRequest: function (url: string, init?: RequestOptions, timeout?: number): Promise<Response> {
-    return new Promise<Response>((resolve, reject) => {
-      uni.request({
-        url: url,
-        timeout: timeout,
-        ...init,
-        success(res) {
-          const response = new Response(url, res.data, {
-            headers: res.header,
-            status: res.statusCode,
-          }, 'success');
-          resolve(response);
-        },
-        fail(res) {
-          reject(res);
-        },
-      })
-    });
-  }
-};
-
-export default uniappImplementer;

+ 0 - 48
src/common/request/implementer/WebFetch.ts

@@ -1,48 +0,0 @@
-import type { RequestCacheStorage, RequestOptions } from "../core/RequestCore";
-import type { RequestImplementer } from "../core/RequestImplementer";
-
-const fetchImplementer : RequestImplementer = {
-  getCache: async function (key: string) {
-    const v = localStorage.getItem(key);
-    return v ? JSON.parse(v) as RequestCacheStorage : null;
-  },
-  setCache: async function (key: string, value: RequestCacheStorage|null) {
-    localStorage.setItem(key, JSON.stringify(value));
-  },
-  doRequest: function (url: string, init?: RequestOptions, timeout?: number): Promise<Response> {
-    // 创建 AbortController 实例
-    const controller = new AbortController();
-    const { signal } = controller;
-
-    // 设置超时逻辑
-    const timeoutId = setTimeout(() => {
-      controller.abort(); // 超时后取消请求
-    }, timeout);
-
-    const header = init?.header || {};
-    let body : string|FormData|undefined;
-    if (init?.data instanceof FormData)
-      body = init.data; 
-      if (header['Content-Type'] == 'multipart/form-data')
-        delete header['Content-Type']; //由浏览器自己指定boundary
-    else if (typeof init?.data === 'object') {
-      body = JSON.stringify(init.data); 
-    }
-
-
-    // 发起 fetch 请求
-    const response = fetch(url, { 
-      headers: header,
-      method: init?.method,
-      body,
-      signal 
-    });
-
-    // 请求完成后清除超时
-    response.finally(() => clearTimeout(timeoutId));
-    return response
-  }
-};
-
-
-export default fetchImplementer;

+ 0 - 33
src/common/request/index.ts

@@ -1,33 +0,0 @@
-import type { DataModel } from "@imengyu/js-request-transform";
-import { RequestCoreInstance } from "./core/RequestCore";
-
-/**
- * 基础请求模块
- *
- * 说明:
- *  此处提供的是一个默认请求模块,演示了如何写自己的请求模块,
- *  你可以参照这个类来写你自己的请求模块,并添加拦截器、错误处理、数据处理等等功能。
- *
- * Author: imengyu
- * Date: 2022/03/25
- *
- * Copyright (c) 2021 imengyu.top. Licensed under the MIT License.
- * See License.txt in the project root for license information.
- */
-
-
-/**
- * 基础请求模块
- * @deprecated 请使用 AuthServerRequestModule 或 AppServerRequestModule
- */
-export class DefaultRequestModule<T extends DataModel> extends RequestCoreInstance<T> {
-  constructor() {
-    super();
-    this.config.requestInceptor = (url, req) => {
-      //登录相关Token添加
-      return { newUrl: url, newReq: req };
-    };
-  }
-}
-
-export default new DefaultRequestModule<DataModel>();

+ 0 - 52
src/common/request/utils/AllType.ts

@@ -1,52 +0,0 @@
-/**
- * 请求工具所使用的类定义
- *
- * Author: imengyu
- * Date: 2022/03/25
- *
- * Copyright (c) 2021 imengyu.top. Licensed under the MIT License.
- * See License.txt in the project root for license information.
- */
-
-/**
- * 空的结构
- */
-export type TypeEmpty = Record<string, never>;
-
-/**
- * 可保存数据
- */
-export type TypeSaveable =
-  | TypeEmpty
-  | string
-  | number
-  | null
-  | undefined
-  | bigint
-  | boolean;
-/**
- * 可保存数据
- */
-export type TypeAll =
-  | TypeEmpty
-  | unknown
-  | object
-  | undefined
-  | string
-  | bigint
-  | number
-  | boolean;
-
-/**
- * URL参数
- */
-export interface QueryParams {
-  /**
-   * URL参数
-   */
-  [index: string]: TypeAll;
-}
-
-export interface HeaderType {
-  [key: string]: string;
-}

+ 0 - 84
src/common/request/utils/Utils.ts

@@ -1,84 +0,0 @@
-/**
- * 请求工具所使用的工具函数
- *
- * 功能介绍:
- *  提供了一些处理工具函数,方便使用。
- *
- * Author: imengyu
- * Date: 2022/03/25
- *
- * Copyright (c) 2021 imengyu.top. Licensed under the MIT License.
- * See License.txt in the project root for license information.
- */
-
-/* eslint-disable no-bitwise */
-import type { KeyValue } from "@imengyu/js-request-transform/dist/DataUtils";
-import type { TypeSaveable } from "./AllType";
-
-export function isNullOrEmpty(val: unknown) {
-  return !val || typeof val === 'undefined' || val === '';
-}
-export function simpleClone<T>(obj: T) : T {
-  let temp: KeyValue|Array<KeyValue>|null = null;
-  if (obj instanceof Array) {
-    temp = obj.concat();
-  }
-  else if (typeof obj === 'object') {
-    temp = {} as KeyValue;
-    for (const item in obj) {
-      const val = (obj as unknown as KeyValue)[item];
-      if (val === null) temp[item] = null;
-      else (temp as KeyValue)[item] = simpleClone(val) as TypeSaveable;
-    }
-  } else {
-    temp = obj as unknown as KeyValue;
-  }
-  return temp as unknown as T;
-}
-/**
- * 计算字符串的哈希值
- * @param {string} str
- */
-export function stringHashCode(str: string) {
-  return '' + (str.split("").reduce(function(a, b) {
-    a = (a << 5) - a + b.charCodeAt(0);
-    return (a & a);
-  }, 0));
-}
-
-export function checkIfStringAllEnglish(str: string) {
-  return /^[\x00-\x7F]+$/.test(str)
-}
-
-export function appendGetUrlParams(url: string, key: string, value: any) {
-  if (!url.includes(`?${key}`) && !url.includes(`&${key}`)) {
-    if (url.includes('?'))
-      url = url + '&' + key + '=' + value;
-    else
-      url = url + '?' + key + '=' + value;
-  }
-  return url;
-}
-export function appendPostParams(source: any, key: string, value: any) {
-  if (source instanceof FormData && !source.has(key))
-    source.append(key, value);
-  else if (typeof source === 'object' && source[key] === undefined)
-    source = { ...source, [key]: value };
-  return source;
-}
-
-export function transformSomeToArray(source: any) {
-  if (typeof source === 'string') 
-    return source.split(','); 
-  if (typeof source === 'object') {
-    if (source instanceof Array)
-      return source; 
-    else {
-      const arr = [];
-      for (const key in source)
-        arr.push(source[key]);
-      return arr;
-    }
-  }
-  return source;
-}

+ 1 - 1
src/stores/auth.ts

@@ -1,5 +1,5 @@
 import UserApi, { LoginResult, UserInfo } from "@/api/auth/UserApi";
-import { RequestSharedData } from "@/common/request/core/RequestSharedData";
+import { RequestSharedData } from "@/api/RequestSharedData";
 import { defineStore } from "pinia"
 
 const STORAGE_KEY = 'authInfo';