微信小程序请求封装

420 阅读2分钟

在小程序开发中难免会用到接口请求 ,将接口请求的封装做到精致好用是一个优秀的小程序开发者不可或缺的品质。

const app = getApp();
let { baseUrl } = app.globalData;
const loginUrl = '/pages/loginIteration/loginMethod'; // login地址

// 日志
const log = wx.getRealtimeLogManager ? wx.getRealtimeLogManager() : null
const err_log = () => {
  if (!log) return
  log.error.apply(log, arguments)
}

// 获取当前路径
const getCurrentPath = () => {
  const history = getCurrentPages();
  const currentPage = history[history.length - 1];
  return currentPage.route;
}

// loading配置,请求次数统计
const startLoading = () =>{
  wx.showLoading({
    title: 'Loading...',
    icon: 'none',
    mask: true
  })
}

const endLoading = () =>{
  wx.hideLoading();
}

// 声明一个对象用于存储请求个数
let needLoadingRequestCount = 0;
const showFullScreenLoading = () => {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
};
const tryHideFullScreenLoading = () =>{
  needLoadingRequestCount--;
  if (needLoadingRequestCount <= 1) {
    endLoading();
    return;    
  };
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
};

const request = (url, method, data, header) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      header: header,
      data: data,
      method: method,
      success: (res) => {
        resolve(res);
      },
      fail: (res) => {
        reject(res);
      }
    });
  })
}

// get/post请求
const fun = async (url, method, params, header, quiet = false,) => {
  params = params || {};
  header = header || {};
  // 根据后端需求增加请求头的参数
  const accountInfo = wx.getStorageSync("accountInfo");
  header.token = accountInfo.token || '';
  header.userId = accountInfo.userId || '';
  if(!quiet) {
    wx.showNavigationBarLoading();
    showFullScreenLoading();
  }
  try {
    const { data: resData } = await request(url, method, params, header);
    if (!quiet) {
      tryHideFullScreenLoading();
      wx.hideNavigationBarLoading();
    }
    const { code, errCode, msg, data, returnCode } = resData;
    if (code === '1' || returnCode === 200) {
      return Promise.resolve(resData);
    } else if (code === '1110001') {
      wx.showToast({
        title: '您的账号在别处登录,您已被迫下线',
        icon: "none"
      });
      wx.redirectTo({
        url: loginUrl
      });
      // 被迫下线时清除所有用户信息 主动退出登录
      wx.removeStorageSync('accountInfo');
      return Promise.reject(resData);
    } else {
      wx.showToast({
        title: msg,
        icon: "none",
      });
      return Promise.reject(resData);
    }
  } catch (err) {
    if(!quiet) {
      tryHideFullScreenLoading();
      wx.hideNavigationBarLoading();
      wx.showToast({
        title: '服务器异常,请稍后再试',
        icon: "none",
      });
    }
    return Promise.reject(err);
  }
}

// 上传
const uploadFile = (url, filePath, name = 'file' ) => {
  let header = {};
  wx.showNavigationBarLoading();
  showFullScreenLoading();
  let promise = new Promise( (resolve, reject) => {
    wx.uploadFile({
      url: baseUrl + url,
      filePath: filePath,
      name: name,
      header: header,
      success: (res) => {
        resolve(res.data);
        tryHideFullScreenLoading();
      },
      fail: () => {
        reject({ error: '网络错误', code: 0 });
        tryHideFullScreenLoading();
      },
      complete: () => {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
      }
    });
  });
  return promise;
}

module.exports = {
  "get": (url, data, header) => {
    return fun(url, "GET", data, header);
  },
  "post": (url, data) => {
    return fun(url, "POST", data, {
      'Content-Type': 'application/x-www-form-urlencoded'
    });
  },
  "postQuiet": (url, data) => {
    return fun(url, "POST", data, {
      'Content-Type': 'application/x-www-form-urlencoded'
    }, true);
  },
  'postJSON': (url, data) => {
    return fun(url, 'POST', data, { 'content-type': 'application/json'})
  },
  'postJSONQuiet': (url, data) => {
    return fun(url, 'POST', data, { 'content-type': 'application/json'}, true)
  },
  upload: (url, filePath, name ) => {
    return uploadFile(url, filePath, name);
  }
};