fetch-api.js 7.12 KB
let config = require('./../config');
let Storage = require('./../utils/stroage');
let util = require('./../utils/util');
let Router = require('./../router/index');
let Encrypt = require('./../utils/enc/enc');
let api = require('./api');
const errMsg = '服务异常,请稍后重试';

/**
 * 重新获取 sessionId
 * 1.重新获取wxcode,
 * 2.调用login方法,传wxcode,给后端重新换取js_session
 * @returns
 */
function login() {
  return new Promise((resolve, reject) => {
    // my.login({
    //   success: (res) => {

    let res = {
      code: util.uuid()
    }

    let baseUrl = config.NET_CONFIG.BASE_API + config.NET_CONFIG.API_PREFIX;
    let header = {
      '-kd-platform-env': config.ENV,
      '-kd-platform-module': config.NET_CONFIG.MODULE_CODE
    }


    let app = getApp();
    let globalData = app && app.globalData || null
    let data = {
      code: res.code,
      miniproChannel: globalData.channelCode || "",
      channelCode: globalData.channelCode || "",
      parentMemberCode: globalData.parentMemberCode || "",
      platform: "minipro",
    };

    data = Encrypt.makeEncrypt(data);
    my.request({
      // url: baseUrl + api.wxLogin,
      url: baseUrl + api.login,
      sid: false,
      data: data,
      method: 'POST',
      header: header,
      success: (res) => {
        let {
          code,
          content
        } = res.data;
        if (code == 200 && content.sessionId) {
          Storage.setItem('sessionId', content.sessionId); // 保存新的sessionId
          resolve();
        } else {
          reject();
        }
      }
    })
    // }
    // });

  });
}


/**
 * 检查并埋下sessionId
 * @param {*} sid 接口是否需要sessionId
 * @returns
 */
function checkSessionId(sid) {
  return new Promise((resolve, reject) => {
    let sessionId = Storage.getItem('sessionId');
    if (sid) {
      // 拥有sessionId
      if (sessionId) {
        resolve();
      } else {
        // 重新获取 sessionId
        login().then((result) => {
          resolve();
        }).catch((err) => {
          reject();
        });
      }
    } else {
      // 不需要 sessionId 忽略
      resolve();
    }
  });
}



function fetchMethod(val) {
  let params = Object.assign({
    loading: false,
    toast: true,
    sid: true,
    mode: "",
    url: "",
    data: null,
    method: "GET",
    enc: false
  }, val);
  let promise = new Promise((resolve, reject) => {
    checkSessionId(params.sid).then(() => {
      doRequest(params).then((result) => {
        resolve(result);
      }).catch((err) => {
        // 404 或 403 错误码的时候需要重新拉一次
        if (err.code == 404 || err.code == 403) {
          login().then((loginRes) => {
            doRequest(params).then((result2) => {
              resolve(result2);
            });
          }).catch((err) => {});
        } else {
          reject(err)
        }
      });
    });
  });
  return promise;
}


/**
 * 做实际请求
 * @param {*} params
 * @returns
 */
function doRequest(params) {
  return new Promise((resolve, reject) => {
    let {
      loading,
      toast,
      mode,
      url,
      data,
      method,
      responseType,
      enc
    } = params;
    let baseUrl = config.NET_CONFIG.BASE_API + config.NET_CONFIG.API_PREFIX;

    // 使用通用接口前缀
    if (mode == "common") baseUrl = config.NET_CONFIG.COMMON_API;
    // 自定义前缀,即不使用前缀
    if (mode == "custom") baseUrl = "";
    if (loading && mode != 'log') my.showLoading({
      content: '加载中',
      mask: true
    });

    // 判断是否开启post方法默认加密
    if (config.NET_CONFIG.IS_POST_ENC && (method == "post" || method == "POST")) {
      enc = true;
    }
    if (enc) data = Encrypt.makeEncrypt(data);

    // 设置请求头
    let header = {
      '-kd-platform-env': config.ENV,
      '-kd-platform-module': config.NET_CONFIG.MODULE_CODE,
      'sessionId': Storage.getItem("sessionId")
    }

    my.request({
      url: baseUrl + url, //请求地址
      data: data, //自定义参数
      method: method || 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: header,
      responseType: responseType,
      success: (result) => {
        // 日志上传不需要处理结果
        if (mode == 'log') return;
        let res = result.data;
        if (responseType == "arraybuffer") {
          if (loading) my.hideLoading();
          resolve(res)
        } else if (res.code === 200) {
          if (loading) my.hideLoading();
          resolve(res.content);
        } else {
          my.hideLoading();
          // 404 不需要toast
          if (toast && res.code != 404) {
            my.showToast({
              content: res.errMsg || errMsg,
              icon: 'none'
            })
          }
          reject(res);
        }
      },
      fail: (err) => {
        my.hideLoading();
      }
    });
  });
}



// --------  业务接口 Start --------

/**
 * 上传文件到恪道
 * @param {*} filePath 图片地址
 * @param {*} subPath 上传目录 (此参数为空则使用 oss目录)
 */
function uploadFile(filePath, subPath) {
  return new Promise((resolve, reject) => {
    if (!subPath && !config.NET_CONFIG.OSS_PATH) {
      throw new Error('请配置上传目录 !');
      reject();
      return;
    }
    my.uploadFile({

      url: config.NET_CONFIG.BASE_API + config.NET_CONFIG.API_PREFIX + api.uploadFile,
      filePath: filePath,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data',
        '-kd-platform-env': config.ENV,
        '-kd-platform-module': config.NET_CONFIG.MODULE_CODE,
      },
      formData: {
        subPath: subPath || config.NET_CONFIG.OSS_PATH
      },
      success(res) {
        let result = JSON.parse(res.data).content;
        resolve(result);
      },
      fail() {
        reject()
      },
      complete() {}
    })
  });
}


/**
 * 上传多个文件到服务器
 * urlList 需要上传的图片地址  (my.chooseImage 的 paths列表)
 *
 */
function uploadFileMultiple(filePathList, subPath) {
  return new Promise((resolve, reject) => {
    if (!subPath && !config.NET_CONFIG.OSS_PATH) {
      throw new Error('请配置上传目录 !');
      reject();
      return;
    }
    console.log("config.NET_CONFIG.COMMON_API + api.uploadFile:", config.NET_CONFIG.COMMON_API + api.uploadFile);
    my.showLoading({
      content: `加载中`
    })
    console.log("filePathList:", filePathList);
    if (filePathList && filePathList.length > 0) {
      let promiseList = [];
      filePathList.forEach(element => {
        let promiseItem = new Promise((resolve2, reject2) => {
          uploadFile(element, subPath).then((result2) => {
            resolve2(result2)
          }).catch((err) => {
            reject2();
          });
        });
        promiseList.push(promiseItem);
      });
      console.log("promiseList:", promiseList);
      Promise.all(promiseList).then(uploadFiles => {
        my.hideLoading()
        resolve(uploadFiles)
      }, reason => {
        my.hideLoading()
        reject();
      });
    } else {
      my.hideLoading()
      resolve([]);
    }
  });
}

module.exports = {
  fetchMethod,
  uploadFile,
  uploadFileMultiple
}