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

/**
 * 1.业务接口返回404时,会自动调用自定义login接口重拉sessionId,成功后会重新调用该业务接口
 * 2.当自定义login接口返回状态码不为200时,弹出授权登陆
 */

function wxLogin() {
  return new Promise((resolve, reject) => {
    wx.login({
      success: function (res) {
        // isWxLogin = true;
        Store.setItem('wxcode', res.code);
        resolve();
      }
    });
  });
}


// 检查并获取sessionid
function checkSessionId(sid) {
  return new Promise((resolve, reject) => {
    if (!sid) {
      resolve();
      return;
    }
    let sessionId = Store.getItem('sessionId');
    if (sessionId) {
      resolve();
    } else {
      // 没有sessionId则获取并埋值
      login().then((result) => {
        resolve();
      }).catch((err) => {
        reject();
      });
    }
  });
}

// session丢失
function login() {
  return new Promise((resolve, reject) => {
    wxLogin().then((result) => {
      let baseUrl = config.NET_CONFIG.baseApi;
      wx.request({
        url: baseUrl + '/login',
        sid: false,
        data: {
          code: Store.getItem('wxcode')
        },
        method: 'POST',
        success: function (res2) {
          let {
            code,
            content
          } = res2.data;
          if (code == 200 && content.sessionId) {
            Store.setItem('sessionId', content.sessionId);
            Store.setItem('memberCode', content.memberCode);
            resolve();
          } else {
            wx.hideLoading();
            let pages = getCurrentPages();
            let view = pages[pages.length - 1];
            if (view) {
              try {
                wx.login({
                  success: function (res) {
                    Store.setItem('wxcode', res.code);
                    view.showAuth();
                  }
                });
              } catch (error) {}
            }
            reject();
          }
        }
      })
    })

  });
}

const fetch = function ({
  loading = true,
  toast = true,
  sid = true,
  auth = true,
  mode,
  isMock,
  url,
  data,
  method
}) {
  if (loading && mode != 'log') wx.showLoading();
  // 新建promise对象
  let promise = new Promise((resolve, reject) => {
    /**
     * isMock设置单个接口Mock开启
     * mode:目前针对不同业务的接口进行处理,log标识本地埋点上传
     */
    let baseUrl = config.NET_CONFIG.baseApi;
    if (isMock && mode != 'log') {
      baseUrl = config.MOCKAPI; //环境配置
    }
    // 使用通用接口前缀
    if (mode == "common") {
      baseUrl = config.NET_CONFIG.commonApi
    }
    // 自定义前缀,即不使用前缀
    if (mode == "custom") {
      baseUrl = ""
    }
    checkSessionId(sid).then((result) => {
      wx.request({
        url: baseUrl + url, //请求地址
        data: data, //自定义参数
        method: method || 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {
          sessionId: Store.getItem("sessionId")
        },
        success: function (result) {
          // 日志上传不需要处理结果
          if (mode == 'log') return;
          let res = result.data;
          // 登陆失效拦截,根据项目需要添加自己的配置
          if (res.code == 404) {
            //登陆失效的回调
            Store.clear("sessionId");
            // 404后拉取登陆后再做一次
            login().then((resultLogin) => {
              wx.request({
                url: baseUrl + url, //请求地址
                data: data, //自定义参数
                method: method || 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                header: {
                  sessionId: Store.getItem("sessionId")
                },
                success: function (result) {
                  // 日志上传不需要处理结果
                  if (mode == 'log') return;
                  let res = result.data;
                  if (res.code === 200) {
                    if (loading) {
                      wx.hideLoading();
                    }
                    resolve(res.content);
                  } else {
                    // 有些特殊状况不需要toast 需要弹窗
                    if (toast) {
                      wx.showToast({
                        title: res.errMsg || errMsg,
                        icon: 'none'
                      })
                    } else {
                      wx.hideLoading();
                    }
                    // 返回错误信息
                    reject(res);
                  }
                }
              });
            })
            return;
          }
          // 内部统一的成功code拦截码
          if (res.code === 200) {
            if (loading) {
              wx.hideLoading();
            }
            resolve(res.content);
          } else {
            // 有些特殊状况不需要toast 需要弹窗
            if (toast) {
              wx.showToast({
                title: res.errMsg || errMsg,
                icon: 'none'
              })
            } else {
              wx.hideLoading();
            }
            // 返回错误信息
            reject(res);
          }
        },
        fail: function (e = {
          CODE: -1,
          msg: errMsg,
          errMsg
        }) {
          let msg = e.errMsg;
          if (e.errMsg == 'request:fail timeout') {
            msg = '服务请求超时,请稍后重试'
          }
          wx.showToast({
            title: msg,
            icon: 'none'
          });
          reject(e)
        },
        complete: function () {
          // complete
        }
      })
    })
  });
  return promise;
}

module.exports = {
  fetch
}