快乐的梦鱼 2 týždňov pred
rodič
commit
63962d13fa

+ 4 - 4
package-lock.json

@@ -24,7 +24,7 @@
         "@dcloudio/uni-mp-weixin": "3.0.0-4070620250821001",
         "@dcloudio/uni-mp-xhs": "3.0.0-4070620250821001",
         "@dcloudio/uni-quickapp-webview": "3.0.0-4070620250821001",
-        "@imengyu/imengyu-utils": "^0.0.20",
+        "@imengyu/imengyu-utils": "^0.0.25",
         "@imengyu/js-request-transform": "^0.3.7",
         "async-validator": "^4.2.5",
         "crypto-js": "^4.2.0",
@@ -6031,9 +6031,9 @@
       }
     },
     "node_modules/@imengyu/imengyu-utils": {
-      "version": "0.0.20",
-      "resolved": "https://registry.npmjs.org/@imengyu/imengyu-utils/-/imengyu-utils-0.0.20.tgz",
-      "integrity": "sha512-pPI5fObKE9QBMZtrRrR9U/fht2boPoaC61e4tPoULkLqt8W1Mm1yk11pQgM04HbFMe9TNggoPQJc9ctR3xCOXA==",
+      "version": "0.0.25",
+      "resolved": "https://registry.npmmirror.com/@imengyu/imengyu-utils/-/imengyu-utils-0.0.25.tgz",
+      "integrity": "sha512-xs+8dLnG4o4ssPgtoRUfUq8n64yoyj0rAGQlDsxWy+4BBdEpRowPtznlcaEHWnM5p6PukVfWTr0JVkzKhTa2Vg==",
       "license": "MIT",
       "dependencies": {
         "@imengyu/js-request-transform": "^0.3.6"

+ 1 - 1
package.json

@@ -51,7 +51,7 @@
     "@dcloudio/uni-mp-weixin": "3.0.0-4070620250821001",
     "@dcloudio/uni-mp-xhs": "3.0.0-4070620250821001",
     "@dcloudio/uni-quickapp-webview": "3.0.0-4070620250821001",
-    "@imengyu/imengyu-utils": "^0.0.20",
+    "@imengyu/imengyu-utils": "^0.0.25",
     "@imengyu/js-request-transform": "^0.3.7",
     "async-validator": "^4.2.5",
     "crypto-js": "^4.2.0",

+ 225 - 0
src/api/BaseAppServerRequestModule.ts

@@ -0,0 +1,225 @@
+import BugReporter from "@/common/BugReporter";
+import ApiCofig from "@/common/config/ApiCofig";
+import AppCofig, { isDev } from "@/common/config/AppCofig";
+import { RequestCoreInstance, RequestApiError, UniappImplementer, StringUtils, appendGetUrlParams, appendPostParams, RequestResponse, RequestOptions, type RequestApiInfoStruct, RequestApiResult, type RequestApiErrorType, defaultResponseDataGetErrorInfo, defaultResponseDataHandlerCatch } from "@imengyu/imengyu-utils";
+import type { DataModel, KeyValue, NewDataModel } from "@imengyu/js-request-transform";
+
+/**
+ * 说明:业务相关的请求模块
+ * * 请求数据处理函数。
+ * * 自定义请求模块。
+ * * 自定义错误报告处理函数。
+ */
+
+function matchNotReportMessage(code: number, str: string) {
+  if (ApiCofig.notReportErrorCode.includes(code))
+    return true;
+  for (let i = 0; i < ApiCofig.notReportMessages.length; i++) {
+    if (ApiCofig.notReportMessages[i].test(str))
+      return true;
+  }
+  return false;
+}
+//错误报告处理
+export function reportError<T extends DataModel>(instance: RequestCoreInstance<T>, response: RequestApiError | Error) {
+  if (isDev) {
+    //开发模式下直接弹窗显示
+    if (response instanceof RequestApiError) {
+      uni.showModal({
+        title: `请求错误 ${response.apiName} : ${response.errorMessage}`,
+        content: response.toString() +
+          '\r\n请求接口:' + response.apiName +
+          '\r\n请求地址:' + response.apiUrl +
+          '\r\n请求参数:' + JSON.stringify(response.apiRawReq) +
+          '\r\n返回参数:' + JSON.stringify(response.rawData) +
+          '\r\n状态码:' + response.code +
+          '\r\n信息:' + response.errorCodeMessage,
+        type: 'error',
+        showCancel: false,
+      });
+    } else {
+      uni.showModal({
+        title: '错误报告 代码错误',
+        content: response?.stack || ('' + response),
+        type: 'error',
+        showCancel: false,
+      });
+    }
+  } else {   
+    //生产模式下收集错误信息,报告错误服务器
+    let errMsg = '';
+    if (response instanceof RequestApiError) {
+      BugReporter.reportRequestBug({
+        errorType: response.errorType,
+        errorMessage: response.errorMessage,
+        apiName: response.apiName,
+        apiUrl: response.apiUrl,
+        rawRequest: response.apiRawReq,
+        rawData: response.rawData,
+        code: response.code.toString(),
+        errorCodeMessage: response.errorCodeMessage,
+        data: response.rawData,
+      });
+    } else  {
+      errMsg += '服务出现了异常,请稍后重试或联系客服。';
+      errMsg += '版本:' + AppCofig.version;
+      uni.showModal({
+        title: '抱歉',
+        content: errMsg,
+        showCancel: false,
+      });
+      BugReporter.reportError(response);
+    }
+  }
+}
+
+export class BaseAppServerRequestModule<T extends DataModel> extends RequestCoreInstance<T> {
+  constructor(baseUrl: string) {
+    super(UniappImplementer);
+    this.config.baseUrl = baseUrl;
+    this.config.errCodes = [];
+    //请求拦截器
+    this.config.requestInceptor = (url, req) => {
+      //获取app中的token,追加到头;
+      const app = getApp();
+      if (StringUtils.isNullOrEmpty((req.headers as KeyValue).token as string)) {
+        const t = app?.globalData?.token ?? '';
+        req.headers['token'] = t
+        req.headers['__token__'] = t;
+      }
+      const main_body_user_id = app?.globalData?.userId ?? '';
+      const append_main_body_user_id = !(url.includes('content/content'));
+
+      if (req.method == 'GET') {
+        //追加GET参数
+        url = appendGetUrlParams(url, 'main_body_id', ApiCofig.mainBodyId);
+        //url = appendGetUrlParams(url, 'platform', ApiCofig.platformId);
+        if (append_main_body_user_id)
+          url = appendGetUrlParams(url, 'main_body_user_id', main_body_user_id);
+      } else {
+        req.data = appendPostParams(req.data,'main_body_id', ApiCofig.mainBodyId);
+        //req.data = appendPostParams(req.data,'platform', ApiCofig.platformId);
+        if (append_main_body_user_id)
+          req.data = appendPostParams(req.data,'main_body_user_id', main_body_user_id);
+      } 
+      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
+            );
+          }
+
+          //code == 0 错误
+          if (json.code === 0) {
+            throw createError(json);
+          }
+
+          //处理后端的数据
+          let message = '未知错误';
+          let data = {} as any;
+
+          //后端返回格式不统一,所以在这里处理格式
+          if (typeof json.data === 'object') {
+            data = json.data;
+            message = json.data?.msg || response.statusText;
+          }
+          else {
+            //否则返回上层对象
+            data = json;
+            message = json.msg || response.statusText;
+          }
+
+          return new RequestApiResult(
+            resultModelClass ?? instance.config.modelClassCreator,
+            json?.code || response.status,
+            message,
+            data,
+            json,
+            response.headers,
+            apiInfo
+          );
+        }
+        else {
+          throw createError(json);
+        }
+
+        function createError(json: any): RequestApiError {
+          let errType : RequestApiErrorType = 'unknow';
+          let errString = '';
+          let errCodeStr = '';
+
+          if (typeof json.message === 'string') 
+            errString = json.message;
+          if (typeof json.msg === 'string') 
+            errString += json.msg;
+
+          if (StringUtils.isStringAllEnglish(errString))
+            errString = '服务器返回:' + errString;
+
+          //错误处理
+          if (errString) {
+            //如果后端有返回错误信息,则收集错误信息并返回
+            errType = 'businessError';
+            if (typeof json.data === 'object' && json.data?.errmsg) {
+              errString += '\n' + json.data.errmsg;
+            }
+            if (typeof json.errors === 'object') {
+              for (const key in json.errors) {
+                if (Object.prototype.hasOwnProperty.call(json.errors, key)) {
+                  errString += '\n' + json.errors[key];
+                }
+              }
+            }
+          } else {
+            const res = defaultResponseDataGetErrorInfo(response, json);
+            errType = res.errType;
+            errString = res.errString;
+            errCodeStr = res.errCodeStr;
+          }
+
+          return new RequestApiError(
+            errType,
+            errString,
+            errCodeStr,
+            response.status,
+            null,
+            null,
+            response.headers,
+            apiInfo
+          );
+        }
+      } catch (err) {
+        if (err instanceof RequestApiError) {
+          throw err;
+        }
+        //错误统一处理
+        return new Promise<RequestApiResult<T>>((resolve, reject) => {
+          defaultResponseDataHandlerCatch(method, req, response, null, err as any, apiInfo, response.url, reject, instance);
+        });
+      }
+    };
+    //错误报告处理
+    this.config.responseErrReoprtInceptor = (instance, response) => {
+      return (
+        (response.errorType !== 'businessError' && response.errorType !== 'networkError') ||
+        matchNotReportMessage(response.code, response.errorMessage) === true
+      );
+    };
+    //错误报告处理函数
+    this.config.reportError = reportError;
+  }
+}

+ 44 - 52
src/api/CommonContent.ts

@@ -321,13 +321,12 @@ export class CommonContentApi extends AppServerRequestModule<DataModel> {
     type?: number,
     withself?: boolean,
   ) {
-    return (this.get('/content/category/getCategoryList', '获取分类列表', {
+    const res = await this.get('/content/category/getCategoryList', '获取分类列表', {
       type,
       is_tree: false,
       withself,
-    }))
-      .then(res => transformArrayDataModel<CategoryListItem>(CategoryListItem, res.data2, `获取分类列表`, true))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<CategoryListItem>(CategoryListItem, res.data2, `获取分类列表`, true);
   }
   /**
    * 用于获取某一个分类需要用的子级
@@ -335,16 +334,15 @@ export class CommonContentApi extends AppServerRequestModule<DataModel> {
    * @returns 
    */
   async getCategoryChildList(pid?: number) {
-    return (this.get('/content/category/getCategoryOnlyChildList', '获取分类子级列表', {
+    const res = await this.get('/content/category/getCategoryOnlyChildList', '获取分类子级列表', {
       pid,
-    }))
-      .then(res => transformArrayDataModel<CategoryListItem>(
-        CategoryListItem, 
-        transformSomeToArray(res.data2), 
-        `获取分类列表`, 
-        true
-      ))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<CategoryListItem>(
+      CategoryListItem, 
+      transformSomeToArray(res.data2), 
+      `获取分类列表`, 
+      true
+    );
   }
   /**
    * 主体栏目列表
@@ -352,18 +350,17 @@ export class CommonContentApi extends AppServerRequestModule<DataModel> {
    * @param querys 额外参数
    * @returns 
    */
-  getColumList<T extends DataModel = GetColumContentList>(params: GetColumListParams, modelClassCreator: NewDataModel = GetColumContentList, querys?: QueryParams) {
-    return this.get('/content/content/getMainBodyColumnContentList', `${this.debugName} 主体栏目列表`, {
+  async getColumList<T extends DataModel = GetColumContentList>(params: GetColumListParams, modelClassCreator: NewDataModel = GetColumContentList, querys?: QueryParams) {
+    const res = await this.get('/content/content/getMainBodyColumnContentList', `${this.debugName} 主体栏目列表`, {
       main_body_id: this.mainBodyId,
       model_id: this.modelId,
       ...params.toServerSide(),
       ...querys,
-    })
-      .then(res => ({
-        list: transformArrayDataModel<T>(modelClassCreator, res.data2.list, `${this.debugName} 主体栏目列表`, true),
-        total: res.data2.total as number,
-      }))
-      .catch(e => { throw e });
+    });
+    return {
+      list: transformArrayDataModel<T>(modelClassCreator, res.data2.list, `${this.debugName} 主体栏目列表`, true),
+      total: res.data2.total as number,
+    };
   }
   /**
    * 模型内容列表
@@ -373,8 +370,8 @@ export class CommonContentApi extends AppServerRequestModule<DataModel> {
    * @param querys 额外参数
    * @returns 
    */
-  getContentList<T extends DataModel = GetContentListItem>(params: GetContentListParams, page: number, pageSize: number = 10, modelClassCreator: NewDataModel = GetContentListItem, querys?: QueryParams) {
-    return this.get('/content/content/getContentList', `${this.debugName} 模型内容列表`, {
+  async getContentList<T extends DataModel = GetContentListItem>(params: GetContentListParams, page: number, pageSize: number = 10, modelClassCreator: NewDataModel = GetContentListItem, querys?: QueryParams) {
+    const res = await this.get('/content/content/getContentList', `${this.debugName} 模型内容列表`, {
       ...params.toServerSide(),
       model_id: params.modelId || this.modelId,
       main_body_id: params.mainBodyId || this.mainBodyId,
@@ -382,30 +379,27 @@ export class CommonContentApi extends AppServerRequestModule<DataModel> {
       page,
       pageSize,
       ...querys,
-    })
-      .then(res => {
-        let resList : any = null;
-        let resTotal : any = null;
+    });
+    let resList : any = null;
+    let resTotal : any = null;
 
-        if (res.data2?.list && Array.isArray(res.data2.list)) {
-          resList = res.data2.list;
-          resTotal = res.data2.total ?? resList.length;
-        }
-        else if (res.data2 && Array.isArray(res.data2)) {
-          resList = res.data2;
-          resTotal = resList.length;
-        } else
-          resList = res.data;
+    if (res.data2?.list && Array.isArray(res.data2.list)) {
+      resList = res.data2.list;
+      resTotal = res.data2.total ?? resList.length;
+    }
+    else if (res.data2 && Array.isArray(res.data2)) {
+      resList = res.data2;
+      resTotal = resList.length;
+    } else
+      resList = res.data;
 
-        if (resList === null)
-          return { list: [], total: 0 };
-        
-        return { 
-          list: transformArrayDataModel<T>(modelClassCreator, resList, `${this.debugName} 模型内容列表`, true),
-          total: resTotal as number,
-        }
-      })
-      .catch(e => { throw e });
+    if (resList === null)
+      return { list: [], total: 0 };
+    
+    return { 
+      list: transformArrayDataModel<T>(modelClassCreator, resList, `${this.debugName} 模型内容列表`, true),
+      total: resTotal as number,
+    };
   }
   /**
    * 内容详情
@@ -413,15 +407,13 @@ export class CommonContentApi extends AppServerRequestModule<DataModel> {
    * @param querys 额外参数
    * @returns 
    */
-  getContentDetail<T extends DataModel = GetContentDetailItem>(id: number, modelClassCreator: NewDataModel = GetContentDetailItem, modelId?: number, querys?: QueryParams) {
-    return this.get('/content/content/getContentDetail', `${this.debugName} (${id}) 内容详情`, {
+  async getContentDetail<T extends DataModel = GetContentDetailItem>(id: number, modelClassCreator: NewDataModel = GetContentDetailItem, modelId?: number, querys?: QueryParams) {
+    return (await this.get('/content/content/getContentDetail', `${this.debugName} (${id}) 内容详情`, {
       main_body_id: this.mainBodyId,
       model_id: modelId ?? this.modelId,
       id,
       ...querys,
-    }, modelClassCreator)
-      .then(res => res.data as T)
-      .catch(e => { throw e });
+    }, modelClassCreator)).data as T;
   }
   /**
    * 上传文件到服务器
@@ -435,7 +427,7 @@ export class CommonContentApi extends AppServerRequestModule<DataModel> {
       let req : RequestOptions = {
         method: 'POST',
         data: data,
-        header: {},
+        headers: {},
       }
       if (this.config.requestInceptor) {
         const { newReq, newUrl } = this.config.requestInceptor(url, req);
@@ -445,7 +437,7 @@ export class CommonContentApi extends AppServerRequestModule<DataModel> {
       const task = uni.uploadFile({
         url: url,
         name,
-        header: req.header,
+        header: req.headers,
         filePath: file,
         formData: data,
         fileType,

+ 12 - 307
src/api/RequestModules.ts

@@ -1,329 +1,34 @@
 
 /**
- * 这里写的是业务相关的:
- * * 请求数据处理函数。
- * * 自定义请求模块。
- * * 自定义错误报告处理函数。
+ * 说明:
+ * * 不同服务器的请求模块。
  */
 
-import BugReporter from "@/common/BugReporter";
-import AppCofig, { isDev } from "../common/config/AppCofig";
+import { isDev } from "../common/config/AppCofig";
 import ApiCofig from "@/common/config/ApiCofig";
-import { 
-  RequestCoreInstance, RequestOptions, RequestApiError, RequestApiResult, type RequestApiErrorType,
-  defaultResponseDataGetErrorInfo, defaultResponseDataHandlerCatch,
-  RequestResponse,
-  UniappImplementer,
-  appendGetUrlParams, 
-  appendPostParams,
-  StringUtils,
-} from "@imengyu/imengyu-utils";
-import type { DataModel, KeyValue, NewDataModel } from "@imengyu/js-request-transform";
+import { appendGetUrlParams } from "@imengyu/imengyu-utils";
+import type { DataModel } from "@imengyu/js-request-transform";
+import { BaseAppServerRequestModule } from "./BaseAppServerRequestModule";
 
-/**
- * 不报告错误的 code
- */
-const notReportErrorCode = [401,403,404] as number[];
-const notReportMessages = [
-  /请登录/g,
-  /认领/g,
-  /请授权绑定手机号/g,
-] as RegExp[];
-function matchNotReportMessage(str: string) {
-  for (let i = 0; i < notReportMessages.length; i++) {
-    if (notReportMessages[i].test(str))
-      return true;
-  }
-  return false;
-}
-
-//请求拦截器
-function requestInceptor(url: string, req: RequestOptions) {
-  //获取store中的token,追加到头;
-  if (StringUtils.isNullOrEmpty((req.header as KeyValue).token as string)) {
-    const t = getApp()?.globalData?.token ?? '';
-    req.header['token'] = t
-    req.header['__token__'] = t;
-  }
-  const main_body_user_id = getApp()?.globalData?.userId ?? '';
-  const append_main_body_user_id = 
-    !(url.includes('content/content'));
-
-  if (req.method == 'GET') {
-    //追加GET参数
-    url = appendGetUrlParams(url, 'main_body_id', ApiCofig.mainBodyId);
-    //url = appendGetUrlParams(url, 'platform', ApiCofig.platformId);
-    if (append_main_body_user_id)
-      url = appendGetUrlParams(url, 'main_body_user_id', main_body_user_id);
-  } else {
-    req.data = appendPostParams(req.data,'main_body_id', ApiCofig.mainBodyId);
-    //req.data = appendPostParams(req.data,'platform', ApiCofig.platformId);
-    
-    if (append_main_body_user_id)
-      req.data = appendPostParams(req.data,'main_body_user_id', main_body_user_id);
-  } 
-  return { newUrl: url, newReq: req };
-}
-//响应数据处理函数
-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) => {
-      if (response.ok) {
-        if (!json) {
-          reject(new RequestApiError(
-            'businessError',
-            '后端未返回数据',
-            '',
-            response.status,
-            null,
-            null,
-            req,
-            apiName,
-            response.url
-          ));
-          return;
-        }
-
-        //code == 0 错误
-        if (json.code === 0) {
-          handleError();
-          return;
-        }
-
-        //处理后端的数据
-        let message = '未知错误';
-        let data = {} as any;
-
-        //后端返回格式不统一,所以在这里处理格式
-        if (typeof json.data === 'object') {
-          data = json.data;
-          message = json.data?.msg || response.statusText;
-        }
-        else {
-          //否则返回上层对象
-          data = json;
-          message = json.msg || response.statusText;
-        }
-
-        resolve(new RequestApiResult(
-          resultModelClass ?? instance.config.modelClassCreator,
-          json?.code || response.status,
-          message,
-          data,
-          json
-        ));
-      }
-      else {
-        handleError();
-      }
-
-      function handleError() {
-        let errType : RequestApiErrorType = 'unknow';
-        let errString = '';
-        let errCodeStr = '';
-
-        if (typeof json.message === 'string') 
-          errString = json.message;
-        if (typeof json.msg === 'string') 
-          errString += json.msg;
-
-        if (StringUtils.isStringAllEnglish(errString))
-          errString = '服务器返回:' + errString;
-
-        //错误处理
-        if (errString) {
-          //如果后端有返回错误信息,则收集错误信息并返回
-          errType = 'businessError';
-          if (typeof json.data === 'object' && json.data?.errmsg) {
-            errString += '\n' + json.data.errmsg;
-          }
-          if (typeof json.errors === 'object') {
-            for (const key in json.errors) {
-              if (Object.prototype.hasOwnProperty.call(json.errors, key)) {
-                errString += '\n' + json.errors[key];
-              }
-            }
-          }
-        } else {
-          const res = defaultResponseDataGetErrorInfo(response, json);
-          errType = res.errType;
-          errString = res.errString;
-          errCodeStr = res.errCodeStr;
-        }
-
-        reject(new RequestApiError(
-          errType,
-          errString,
-          errCodeStr,
-          response.status,
-          null,
-          null,
-          req,
-          apiName,
-          response.url
-        ));
-      }
-    }).catch((err) => {
-      //错误统一处理
-      defaultResponseDataHandlerCatch(method, req, response, null, err, apiName, response.url, reject, instance);
-    });
-  });
-}
-//错误报告处理
-function responseErrReoprtInceptor<T extends DataModel>(instance: RequestCoreInstance<T>, response: RequestApiError) {
-  return (
-    (response.errorType !== 'businessError' && response.errorType !== 'networkError') ||
-    notReportErrorCode.indexOf(response.code) >= 0 ||
-    matchNotReportMessage(response.errorMessage) === true
-  );
-}
-
-//错误报告处理
-export function reportError<T extends DataModel>(instance: RequestCoreInstance<T>, response: RequestApiError | Error) {
-  if (isDev) {
-    if (response instanceof RequestApiError) {
-      uni.showModal({
-        title: `请求错误 ${response.apiName} : ${response.errorMessage}`,
-        content: response.toString() +
-          '\r\n请求接口:' + response.apiName +
-          '\r\n请求地址:' + response.apiUrl +
-          '\r\n请求参数:' + JSON.stringify(response.rawRequest) +
-          '\r\n返回参数:' + JSON.stringify(response.rawData) +
-          '\r\n状态码:' + response.code +
-          '\r\n信息:' + response.errorCodeMessage,
-        type: 'error',
-        showCancel: false,
-      });
-    } else {
-      uni.showModal({
-        title: '错误报告 代码错误',
-        content: response?.stack || ('' + response),
-        type: 'error',
-        showCancel: false,
-      });
-    }
-  } else {    
-    let errMsg = '';
-    if (response instanceof RequestApiError) {
-      BugReporter.reportRequestBug({
-        errorType: response.errorType,
-        errorMessage: response.errorMessage,
-        apiName: response.apiName,
-        apiUrl: response.apiUrl,
-        rawRequest: response.rawRequest,
-        rawData: response.rawData,
-        code: response.code.toString(),
-        errorCodeMessage: response.errorCodeMessage,
-        data: response.rawData,
-      });
-    } else  {
-      errMsg += '服务出现了异常,请稍后重试或联系客服。';
-      errMsg += '版本:' + AppCofig.version;
-
-      uni.showModal({
-        title: '抱歉',
-        content: errMsg,
-        showCancel: false,
-      });
-      BugReporter.reportError(response);
-    }
-  }
-}
 
 /**
- * App服务请求模块
+ * 主应用服务请求模块
  */
-export class AppServerRequestModule<T extends DataModel> extends RequestCoreInstance<T> {
+export class AppServerRequestModule<T extends DataModel> extends BaseAppServerRequestModule<T> {
   constructor() {
-    super(UniappImplementer);
-    this.config.baseUrl = ApiCofig.serverProd;
-    this.config.errCodes = []; //
-    this.config.requestInceptor = requestInceptor;
-    this.config.responseDataHandler = responseDataHandler;
-    this.config.responseErrReoprtInceptor = responseErrReoprtInceptor;
-    this.config.reportError = reportError;
+    super(isDev ? ApiCofig.server.Dev : ApiCofig.server.Prod);
   }
 }
+
 /**
  * 地图服务请求模块
  */
-export class MapServerRequestModule<T extends DataModel> extends RequestCoreInstance<T> {
+export class MapServerRequestModule<T extends DataModel> extends BaseAppServerRequestModule<T> {
   constructor() {
-    super(UniappImplementer);
-    this.config.baseUrl = 'https://restapi.amap.com';
-    this.config.errCodes = []; //
+    super('https://restapi.amap.com');
     this.config.requestInceptor = (url, req) => {
       url = appendGetUrlParams(url, 'key', ApiCofig.amapServerKey);
       return { newUrl: url, newReq: req };
     };
-    this.config.responseDataHandler = (response, req, resultModelClass, instance, apiName) => {
-        return new Promise<RequestApiResult<T>>((resolve, reject) => {
-          const method = req.method || 'GET';
-          response.json().then((json) => {
-            if (response.ok) {
-              if (!json) {
-                reject(new RequestApiError(
-                  'businessError',
-                  '后端未返回数据',
-                  '',
-                  response.status,
-                  null,
-                  null,
-                  req,
-                  apiName,
-                  response.url
-                ));
-                return;
-              }
-              if (json.status != '1') {
-                handleError();
-                return;
-              }
-              resolve(new RequestApiResult(
-                resultModelClass ?? instance.config.modelClassCreator,
-                json?.code || response.status,
-                json.info,
-                json,
-                json
-              ));
-            }
-            else {
-              handleError();
-            }
-
-            function handleError() {
-              let errType : RequestApiErrorType = 'unknow';
-              let errString = json.info;
-              let errCodeStr = json.infocode;
-              if (errString) {
-                errType = 'businessError';
-              } else {
-                const res = defaultResponseDataGetErrorInfo(response, json);
-                errType = res.errType;
-                errString = res.errString;
-                errCodeStr = res.errCodeStr;
-              }
-
-              reject(new RequestApiError(
-                errType,
-                errString,
-                errCodeStr,
-                response.status,
-                null,
-                null,
-                req,
-                apiName,
-                response.url
-              ));
-            }
-          }).catch((err) => {
-            //错误统一处理
-            defaultResponseDataHandlerCatch(method, req, response, null, err, apiName, response.url, reject, instance);
-          });
-        });
-    };
-    this.config.responseErrReoprtInceptor = responseErrReoprtInceptor;
-    this.config.reportError = reportError;
   }
 }

+ 12 - 12
src/api/auth/UserApi.ts

@@ -90,34 +90,34 @@ export class UserApi extends AppServerRequestModule<DataModel> {
     raw_data: string,
     signature: string,
   }) {
-    return (await this.post('/village/volunteer/third', {
+    return (await this.post('/village/volunteer/third', '登录', {
       appid: AppCofig.appId,
       ...data,
-    }, '登录', undefined, LoginResult)).data as LoginResult;
+    }, undefined, LoginResult)).data as LoginResult;
   }
   async login(data: {
     account: string,
     password: string,
   }) {
-    return (await this.post('/user/login', data, '登录', undefined, LoginResult)).data as LoginResult;
+    return (await this.post('/user/login', '登录', data, undefined, LoginResult)).data as LoginResult;
   }
   async loginAdmin(data: {
     account: string,
     password: string,
   }) {
-    return (await this.post('/user/adminLogin', {
+    return (await this.post('/user/adminLogin', '登录', {
       account: data?.account,
       password: data?.password,
-    }, '登录', undefined, LoginResult)).data as LoginResult;
+    }, undefined, LoginResult)).data as LoginResult;
   }
   async updatePassword(data: {
     newpassword: string,
     oldpassword: string,
   }) {
-    return (await this.post('/content/main_body_user/changepwd', data, '更新密码'))
+    return (await this.post('/content/main_body_user/changepwd', '更新密码', data))
   }
   async getUserInfo() {
-    return (await this.post('/content/main_body_user/getMainBodyUser', {}, '获取用户信息', undefined, UserInfo)).data as UserInfo;
+    return (await this.post('/content/main_body_user/getMainBodyUser', '获取用户信息', {}, undefined, UserInfo)).data as UserInfo;
   }  
   async updateUserInfo(data: {
     nickname?: string,
@@ -125,7 +125,7 @@ export class UserApi extends AppServerRequestModule<DataModel> {
     intro?: string,
     password?: string,
   }) {
-    return (await this.post('/content/main_body_user/editMainBodyUser', data, '更新用户信息'))
+    return (await this.post('/content/main_body_user/editMainBodyUser', '更新用户信息', data))
   }
   async updateSystemUserInfo(data: {
     username?: string,
@@ -133,18 +133,18 @@ export class UserApi extends AppServerRequestModule<DataModel> {
     avatar?: string,
     bio?: string,
   }) {
-    return (await this.post('/user/profile', {
+    return (await this.post('/user/profile', '更新用户信息', {
       username: data.username,
       nickname: data?.nickname,
       avatar: data?.avatar,
       bio: data?.bio,
-    }, '更新用户信息'))
+    }))
   }
   async refresh() {
-    return (await this.post('/ich/inheritor/refresh', {}, '刷新token', undefined, LoginResult)).data as LoginResult;
+    return (await this.post('/ich/inheritor/refresh', '刷新token', {}, undefined, LoginResult)).data as LoginResult;
   }
   async checkUserAuthed() {
-    return await this.post('/village/village/getVillageList', {}, '检查用户是否登录');
+    return await this.post('/village/village/getVillageList', '检查用户是否登录', {});
   }  
 
   

+ 55 - 68
src/api/inhert/VillageApi.ts

@@ -200,124 +200,113 @@ export class VillageApi extends AppServerRequestModule<DataModel> {
   }
 
   async getClaimedVallageList(volunteerId?: string) {
-    
-    return (this.get('/village/village/getVillageList', '获取已认领村落', {
+    const res = await this.get('/village/village/getVillageList', '获取已认领村落', {
       village_volunteer_id: volunteerId,
-    })) 
-      .then(res => transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true);
   }
   async getCanClaimVallageList() {
-    
-    return (this.get('/village/village/getClaimList', '可认领村落列表', {
+    const res = await this.get('/village/village/getClaimList', '可认领村落列表', {
       main_body_id: 2,
-    })) 
-      .then(res => transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true);
   }
   async claimVallage(data: any) {
-    return (this.post('/village/village/addVillageClaim', {
-      ...data
-    }, '认领村落')) ;
+    return this.post('/village/village/addVillageClaim', '认领村落', data);
   }
   async getVallageList(level?: number, status?: number) {
-    
-    return (this.get('/village/village/getList', '村落列表', {
+    const res = await this.get('/village/village/getList', '村落列表', {
       history_level: level,
       status,
-    })) 
-      .then(res => transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true);
   }
   async getVolunteerInfo() {
-    
-    return (await this.post('/village/volunteer/getInfo', {
-    }, '获取志愿者信息', undefined, VolunteerInfo)).data as VolunteerInfo
+    const res = await this.post('/village/volunteer/getInfo', '获取志愿者信息', {}, undefined, VolunteerInfo);
+    return res.data as VolunteerInfo;
   }
   async getVolunteerRanklist(category?: number) {
-    return (this.post('/village/volunteer/getRanklist', {
+    const res = await this.post('/village/volunteer/getRanklist', '志愿者排行榜', {
       category,
-    }, '志愿者排行榜')) 
-      .then(res => transformArrayDataModel<VolunteerRanklistItem>(VolunteerRanklistItem, res.data2, ``, true))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<VolunteerRanklistItem>(VolunteerRanklistItem, res.data2, ``, true);
   }
   
   async addVolunteer(data: VolunteerInfo) {
-    return (this.post('/village/volunteer/add', data.toServerSide(), '添加志愿者')) ;
+    return this.post('/village/volunteer/add', '添加志愿者', data.toServerSide());
   }
   async updateVolunteer(data: VolunteerInfo) {
     console.log('updateVolunteer', data.toServerSide());
-    return (this.post('/village/volunteer/save', data.toServerSide(), '更新志愿者')) ;
+    return this.post('/village/volunteer/save', '更新志愿者', data.toServerSide());
   }
   async deleteVolunteer(id: number, villageId: number) {
-    return (this.post('/village/volunteer/del', {
+    return this.post('/village/volunteer/del', '删除志愿者', {
       id,
       village_id: villageId,
-    }, '删除志愿者')) ;
+    });
   }
   async shareAddVolunteer(data: VolunteerInfo) {
-    return (await (this.post('/village/volunteer/shareAdd', data.toServerSide(), '分享添加志愿者', undefined, LoginResult))).data as LoginResult;
+    const res = await this.post('/village/volunteer/shareAdd', '分享添加志愿者', data.toServerSide(), undefined, LoginResult);
+    return res.data as LoginResult;
   }
   async bindVolunteer(data: {
     account: string,
     password: string
   }) {
-    return (await (this.post('/village/volunteer/bindVolunteer', data, '绑定志愿者', undefined, LoginResult))).data as LoginResult;
+    const res = await this.post('/village/volunteer/bindVolunteer', '绑定志愿者', data, undefined, LoginResult);
+    return res.data as LoginResult;
   }
   async bindWechat(data: { code: string }) {
-    return (this.post('/village/volunteer/bindWechat', {
+    return this.post('/village/volunteer/bindWechat', '绑定微信', {
       code: data.code,
       appid: AppCofig.appId
-    }, '绑定微信')) ;
+    });
   }
 
   async getVolunteerInfoByIdAdmin(id: number) {
-    return (await this.post('/village/volunteer/info', {
+    const res = await this.post('/village/volunteer/info', '管理员获取志愿者信息', {
       id,
-    }, '管理员获取志愿者信息', undefined, VolunteerInfo)).data as VolunteerInfo
+    }, undefined, VolunteerInfo);
+    return res.data as VolunteerInfo;
   }
   async getVolunteerInfoById(id: number) {
-    return (await this.post('/village/volunteer/getInfo', {
+    const res = await this.post('/village/volunteer/getInfo', '获取志愿者信息', {
       id,
-    }, '获取志愿者信息', undefined, VolunteerInfo)).data as VolunteerInfo
+    }, undefined, VolunteerInfo);
+    return res.data as VolunteerInfo;
   }
   async getVillageVolunteerList(villageId?: number, status?: number) {
-    return (this.post('/village/volunteer/getList', {
+    const res = await this.post('/village/volunteer/getList', '获取志愿者列表', {
       village_id: villageId,
       status,
-    }, '获取志愿者列表')) 
-      .then(res => transformArrayDataModel<VolunteerInfo>(VolunteerInfo, res.data2 || [], ``, true))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<VolunteerInfo>(VolunteerInfo, res.data2 || [], ``, true);
   }
   async reviewVillageVolunteer(villageId: number, volunteerId: number, status: number) {
-    return (this.post('/village/village/claimReview', {
+    return this.post('/village/village/claimReview', '审核志愿者', {
       village_id: villageId,
       village_volunteer_id: volunteerId,
       status,
-    }, '审核志愿者')) ;
+    });
   }
 
   async getCollectModuleList() {
-    return (this.get('/village/volunteer/getCollectModuleList', '获取采集版块列表', {
-    })) 
-      .then(res => {
-        const result = [] as {
-          value: string,
-          label: string,
-        }[];
-        for (const key in res.data2) {
-          result.push({
-            value: key,
-            label: res.data2[key],
-          })
-        }
-        return result;
-      })
-      .catch(e => { throw e });
+    const res = await this.get('/village/volunteer/getCollectModuleList', '获取采集版块列表', {});
+    const result = [] as {
+      value: string,
+      label: string,
+    }[];
+    for (const key in res.data2) {
+      result.push({
+        value: key,
+        label: res.data2[key],
+      });
+    }
+    return result;
   }
 
   async getCollectModuleMap() {
-    const res = (await this.post('/village/volunteer/getCollectModuleList', {}, '采集板块列表'))
+    const res = await this.post('/village/volunteer/getCollectModuleList', '采集板块列表', {});
     const map = new Map<string, number>();
     if (!res.data2 || typeof res.data2 !== 'object') 
       return map;
@@ -332,20 +321,18 @@ export class VillageApi extends AppServerRequestModule<DataModel> {
   }
 
   async getCatalogList(villageId?: number, volunteerId?: number, pid?: number) {
-    return (this.get('/village/village/getCatalogList', '村落目录列表', {
+    const res = await this.get('/village/village/getCatalogList', '村落目录列表', {
       village_id: villageId,
       village_volunteer_id: volunteerId,
       pid: pid === 0 ? undefined : pid,
-    })) 
-      .then(res => transformArrayDataModel<VillageCatalogListItem>(VillageCatalogListItem, res.data2, `村落目录列表`, true))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<VillageCatalogListItem>(VillageCatalogListItem, res.data2, `村落目录列表`, true);
   }
   async getVillageMenuList(id: number) {
-    return (this.get('/village/menu/getList', '村落菜单列表', {
+    const res = await this.get('/village/menu/getList', '村落菜单列表', {
       village_id: id,
-    })) 
-      .then(res => transformArrayDataModel<VillageMenuListItem>(VillageMenuListItem, res.data2, `村落菜单`, true))
-      .catch(e => { throw e });
+    });
+    return transformArrayDataModel<VillageMenuListItem>(VillageMenuListItem, res.data2, `村落菜单`, true);
   }
 
 }

+ 11 - 23
src/api/inhert/VillageInfoApi.ts

@@ -197,18 +197,6 @@ export class VillageInfoApi extends AppServerRequestModule<DataModel> {
   }
 
   /**
-   * 获取分类列表
-   * @param type 根级类型:1=区域、2=级别、3=文物类型、4=非遗类型、42=事件类型
-   * @param withself 是否返回包含自己:true=是,false=否 ,默认false
-   * @returns 
-   */
-  getCategoryList(
-    type?: number,
-    withself?: boolean,
-  ) {
-    return CommonContent.getCategoryList(type, withself);
-  }
-  /**
    * 用于获取某一个分类需要用的子级
    * @param pid 父级
    * @returns 
@@ -221,10 +209,10 @@ export class VillageInfoApi extends AppServerRequestModule<DataModel> {
     villageId: number,
     villageVolunteerId: number,
   ) {
-    return (this.post(`/village/overview/getInfo`, {
+    return (this.post(`/village/overview/getInfo`, '获取村社概览', {
       village_id: villageId,
       village_volunteer_id: villageVolunteerId,
-    }, '获取村社概览'))
+    }))
       .then(res => transformDataModel(CommonInfoModel, res.data2))
       .catch(e => { throw e });
   }
@@ -240,10 +228,10 @@ export class VillageInfoApi extends AppServerRequestModule<DataModel> {
     id?: number, 
     modelClassCreator: (new () => T) = CommonInfoModel as any
   ) {
-    return (await this.post(`/village/collect/info`, {
+    return (await this.post(`/village/collect/info`, '通用获取信息详情', {
       collect_module_id: collectModuleId,
       id,
-    }, '通用获取信息详情', undefined, modelClassCreator)).data as T
+    }, undefined, modelClassCreator)).data as T
   }
   async getList<T extends DataModel = CommonInfoModel>(
     collectModuleId: number|undefined,
@@ -258,7 +246,7 @@ export class VillageInfoApi extends AppServerRequestModule<DataModel> {
     status?: number|undefined,
     modelClassCreator: (new () => T) = CommonInfoModel as any ,
   ) {
-    return (this.post(`/village/collect/list`, {
+    return (this.post(`/village/collect/list`, '获取信息详情', {
       collect_module_id: collectModuleId,
       [subKey ? subKey : 'type']: subId,
       village_id: villageId,
@@ -267,18 +255,18 @@ export class VillageInfoApi extends AppServerRequestModule<DataModel> {
       page,
       pageSize: pageSize,
       status,
-    }, '获取信息详情'))
+    }))
       .then(res => transformArrayDataModel<T>(modelClassCreator, (res.data2.data || res.data2) ?? [], `获取分类列表`, true))
       .catch(e => { throw e });
   }
 
   async getListForDiscover(page: number, pageSize: number, keywords?: string) {
-    return (this.post(`/village/collect/list`, {
+    return (this.post(`/village/collect/list`, '获取信息详情', {
       page,
       page_size: pageSize,
       keywords,
       status: 4,
-    }, '获取信息详情'))
+    }))
       .then(res => ({
         total: res.data2.total as number,
         list: transformArrayDataModel<CommonInfoModel>(CommonInfoModel, (res.data2.data || res.data2) ?? [], `获取分类列表`, true)
@@ -286,10 +274,10 @@ export class VillageInfoApi extends AppServerRequestModule<DataModel> {
       .catch(e => { throw e });
   }
   async getInfoForDiscover(id: number) {
-    return (await this.post(`/village/collect/info`, {
+    return (await this.post(`/village/collect/info`, '通用获取信息详情', {
       id,
       status: 4,
-    }, '通用获取信息详情', undefined, CommonInfoModel)).data as CommonInfoModel
+    }, undefined, CommonInfoModel)).data as CommonInfoModel
   }
 
   async updateInfo<T extends DataModel>(
@@ -311,7 +299,7 @@ export class VillageInfoApi extends AppServerRequestModule<DataModel> {
     };
     if (subKey)
       res[subKey] = subId;
-    return (await this.post(`/village/collect/save`, res, '通用更新信息详情'));
+    return (await this.post(`/village/collect/save`, '通用更新信息详情', res));
   }
 }
 

+ 17 - 4
src/common/config/ApiCofig.ts

@@ -3,14 +3,27 @@
  * 说明:后端接口配置
  */
 export default {
-  serverDev: 'https://xy.wenlvti.net/api',
-  serverProd: 'https://xy.wenlvti.net/api',
-  amapServerKey: '8fd09264c33678141f609588c432df0e',
+  server: {
+    Dev: 'https://xy.wenlvti.net/api',
+    Prod: 'https://xy.wenlvti.net/api',
+  },
   mainBodyId: 1,
   platformId: 330,
+  amapServerKey: '8fd09264c33678141f609588c432df0e',
   bugReport: {
     server: 'https://update-server1.imengyu.top/bug-submit',
     appId: 1,
     appKey: 'PSzTR2h8c547pNZGERsH3pJRTPhexzc6WSZwdGrQdJFHmXR2',
-  }
+  },
+  /**
+   * 不报告错误的 code
+   */
+  notReportErrorCode: [401],
+  /**
+   * 不报告错误的 message
+   */
+  notReportMessages: [
+    /请登录/g,
+    /认领/g,
+  ] as RegExp[],
 }

+ 1 - 0
src/manifest.json

@@ -64,6 +64,7 @@
             }
         },
         "requiredPrivateInfos" : [ "getLocation", "chooseAddress", "chooseLocation", "choosePoi" ],
+        "nativeTags": [ "official-account-publish" ],
         "plugins" : {}
     },
     "mp-alipay" : {

+ 14 - 0
src/pages/user/index.vue

@@ -38,6 +38,9 @@
       <Cell v-if="userInfo" icon="/static/images/user/icon-quit.png" title="退出登录" showArrow touchable @click="doLogout" />
     </CellGroup>
     <DebugButton />
+    <view class="test">
+      <official-account-publish path="/pages/index" @error="onError"></official-account-publish>
+    </view>
   </FlexCol>
 </template>
 
@@ -64,6 +67,10 @@ const userInfo = computed(() => authStore.isLogged ? authStore.userInfo : null);
 const isBindWx = computed(() => Boolean(userInfo.value?.openId));
 const volunteerInfoLoader = useSimpleDataLoader(async () => await VillageApi.getVolunteerInfo(), true);
 
+function onError(e: any) {
+  console.error(e);
+}
+
 function goUserProfile() {
   userInfo.value ? navTo('/pages/user/update/profile') : navTo('/pages/user/login');
 }
@@ -79,3 +86,10 @@ function doLogout() {
   });
 }
 </script>
+
+<style scoped lang="scss">
+.test {
+  width: 100%;
+  min-height: 50rpx;
+}
+</style>