快乐的梦鱼 1 неделя назад
Родитель
Сommit
926133f795

+ 87 - 2
src/api/RequestModules.ts

@@ -6,9 +6,9 @@
 
 import ApiCofig from "@/common/config/ApiCofig";
 import { isDev } from "../common/config/AppCofig";
-import { appendGetUrlParams } from "@imengyu/imengyu-utils";
+import { appendGetUrlParams, defaultResponseDataHandlerCatch, RandomUtils, RequestApiError, RequestApiResult, type RequestApiInfoStruct, type RequestCoreInstance, type RequestOptions, type RequestResponse } from "@imengyu/imengyu-utils";
 import { BaseAppServerRequestModule } from "./BaseAppServerRequestModule";
-import type { DataModel } from "@imengyu/js-request-transform";
+import type { DataModel, NewDataModel } from "@imengyu/js-request-transform";
 
 
 /**
@@ -31,4 +31,89 @@ export class MapServerRequestModule<T extends DataModel> extends BaseAppServerRe
       return { newUrl: url, newReq: req };
     };
   }
+}
+
+/**
+ * 更新服务请求模块
+ */
+export class UpdateServerRequestModule<T extends DataModel> extends BaseAppServerRequestModule<T> {
+  constructor() {
+    super("https://update-server1.imengyu.top");
+    this.config.requestInterceptor = (url, req) => {
+      if (!req.headers)
+        req.headers = {};
+      req.headers['Authorization'] = JSON.stringify({
+        "apiKey":"MQQDGbn8QfFJ7kStNtkxwifHP4sBTSDd",
+        "apiSecret":"3BNAdR7NXGwfiRmQZkRcRM8PsyHPeBmaay2k2F4TXhGEziXSJ3ceEtH2ApfHsMhR"
+      });
+      return { newUrl: url, newReq: req };
+    };
+    this.config.responseDataHandler = async function responseDataHandler<T extends DataModel>(response: RequestResponse, req: RequestOptions, resultModelClass: NewDataModel | undefined, instance: RequestCoreInstance<T>, apiInfo: RequestApiInfoStruct): Promise<RequestApiResult<T>> {
+      const method = req.method || 'GET';
+      try {
+        const json = await response.json();
+        if (response.ok) {
+          if (!json) {
+            throw new RequestApiError(
+              'businessError',
+              '后端未返回数据',
+              '',
+              response.status,
+              null,
+              null,
+              response.headers,
+              apiInfo
+            );
+          }
+          if (!json.success)
+            throw new RequestApiError(
+              'businessError',
+              json.message,
+              json.code.toString(),
+              json.code,
+              json,
+              json,
+              response.headers,
+              apiInfo
+            );
+          
+          return new RequestApiResult(
+            resultModelClass ?? instance.config.modelClassCreator,
+            json?.code || response.status,
+            json.message,
+            json.data,
+            json,
+            response.headers,
+            apiInfo
+          );
+        }
+        else {
+          throw json;
+        }
+
+      } catch (err) {
+        if (err instanceof RequestApiError) {
+          throw response;
+        }
+        //错误统一处理
+        return new Promise<RequestApiResult<T>>((resolve, reject) => {
+          defaultResponseDataHandlerCatch(method, req, response, null, err as any, apiInfo, response.url, reject, instance);
+        });
+      }
+    };
+  }
+
+  private static readonly DEVICE_UID_KEY = 'deviceUid';
+  private uid = '';
+
+  getDeviceUid() {
+    if (!this.uid) {
+      this.uid = uni.getStorageSync(UpdateServerRequestModule.DEVICE_UID_KEY);
+      if (!this.uid) {
+        this.uid = RandomUtils.genNonDuplicateID(20);
+        uni.setStorageSync(UpdateServerRequestModule.DEVICE_UID_KEY, this.uid);
+      }
+    }
+    return this.uid;
+  }
 }

+ 47 - 0
src/api/system/ConfigurationApi.ts

@@ -0,0 +1,47 @@
+import { UpdateServerRequestModule } from '@/api/RequestModules';
+import { LogUtils } from '@imengyu/imengyu-utils';
+import { DataModel } from '@imengyu/js-request-transform';
+import DefaultConfiguration from './DefaultConfiguration.json';
+
+export const CommonConfigurationConfig = {
+  /**
+   * 应用id
+   */
+  appId: 4,
+  appConfigId: 13,
+}
+
+export interface IConfigurationItem {
+  baseServerUrl: string,
+  articleMark: string,
+  routeListImage: string,
+  routeListImageStyle: Record<string, any>,
+  routeListMarginTop: number,
+}
+
+export class ConfigurationApi extends UpdateServerRequestModule<DataModel> {
+
+  constructor() {
+    super();
+  }
+
+  /**
+   * 获取当前配置,有缓存,会根据激活的历史版本获取对应配置
+   * @returns 
+   */
+  async getConfig() {
+    try {
+      return (await this.get<{
+        data: IConfigurationItem
+      }>('/app-configuration-get', '获取配置', {
+        name: CommonConfigurationConfig.appConfigId,
+        appId: CommonConfigurationConfig.appId,
+        })).data!.data;
+    } catch (error) {
+      LogUtils.printLog("ConfigurationApi", 'error', '获取配置失败,使用默认配置', error);
+      return DefaultConfiguration as IConfigurationItem;
+    }
+  }
+}
+
+export default new ConfigurationApi();

+ 4 - 0
src/api/system/DefaultConfiguration.json

@@ -0,0 +1,4 @@
+{
+  "baseServerUrl": "https://mnwh.wenlvti.net/api",
+  "articleMark": "以上内容摘自:"
+}

+ 31 - 0
src/api/system/useAppConfiguration.ts

@@ -0,0 +1,31 @@
+import { LogUtils } from "@imengyu/imengyu-utils";
+import { inject, provide, ref, type Ref } from "vue";
+import { BaseAppServerRequestUrlManager } from "../BaseAppServerRequestModule";
+import ConfigurationApi, { type IConfigurationItem } from "./ConfigurationApi";
+
+export const APP_CONFIGURATION_KEY = Symbol('APP_CONFIGURATION_KEY');
+
+const TAG = 'useAppConfiguration';
+
+export function useAppConfiguration() {
+  const appConfiguration = ref<IConfigurationItem | null>(null);
+
+  async function loadAppConfiguration() {
+    //获取配置
+    const config = await ConfigurationApi.getConfig();
+    LogUtils.printLog(TAG, 'info', '获取配置', config);
+    appConfiguration.value = config;
+    BaseAppServerRequestUrlManager.notifyUrlConfigUpdated('base-app-server', config.baseServerUrl);
+  }
+
+  provide(APP_CONFIGURATION_KEY, appConfiguration);
+
+  return {
+    loadAppConfiguration,
+    appConfiguration,
+  };
+}
+
+export function injectAppConfiguration() {
+  return inject(APP_CONFIGURATION_KEY) as Ref<IConfigurationItem | null>;
+}