request.js 11.6 KB
var t = require("util.js");

module.exports = {
  uniqueId: "",
  // i: url
  // e: method
  // s: data
  // a: header
  request: function (e, i, o, delay = 1000) {
    this.check_timeout(i, delay, () => {
      var n = this, a = o.header ? o.header : {
        "content-type": "application/x-www-form-urlencoded"
        //"content-type": "application/texts"         
      }, s = "GET" != (e = e.toUpperCase()) && o.data ? t.json2Form(o.data) : o.data;
      i = this.modifyUrl(i, o),
        o.isShowLoading && this.showLoading();
      var req = wx.request(Object.assign({}, o, {
        url: i,
        method: e,
        data: s,
        header: a,
        success: function (t) {
          o.isShowLoading && n.hideLoading(), n.doSuccess(o, t);
        },
        fail(err) {
          o.isShowLoading && n.hideLoading();
          if (err && err.errMsg && err.errMsg.indexOf('timeout') != -1) {
            getApp().globalData.fail_url.set(t.gettimestamp(), i);
            console.log('请求超时url---', getApp().globalData.fail_url);
            n.doTimeOut(o, t);
          } else {
            n.doFail(o, t);
          }
        }
      }));
      return req;
    })
  },
  get: function (t, e) {
    console.log(t, e);
    return this.request("GET", t, e);
  },
  post: function (t, e) {
    this.request("POST", t, e);
  },
  delete: function (t, e) {
    this.request("DELETE", t, e);
  },
  put: function (t, e) {
    this.request("PUT", t, e);
  },


  uploadFile: function (t, e) {
    var i = this;
    t = this.modifyUrl(t, e),
      // console.log("app.request", t, e), 
      e.isShowLoading = void 0 === e.isShowLoading || e.isShowLoading,
      e.isShowLoading && this.showLoading(), wx.uploadFile(Object.assign({}, e, {
        url: t,
        filePath: e.filePath,
        name: e.name,
        success: function (t) {
          i.hideLoading();
          if (t.statusCode == 200)
            t.data = JSON.parse(i.filterJsonData(t.data));
          else { t = { code: -1, msg: '调用接口失败' }; }
          i.doSuccess(e, t);
        },
        fail: function (t) {
          i.hideLoading(), i.doFail(e, t);
        }
      }));
  },

  doSuccess: function (t, e) {
    if (console.log("app.request", e), 1 != t.successReload) {
      if (200 != e.statusCode) return this.showError("请求出错[" + e.statusCode + "]", t),
        !1;

      if (e.data.status != undefined) {
        if (1 != e.data.status) {
          if ("function" == typeof t.failStatus && 0 == t.failStatus(e)) return !1;
          if (-100 == e.data.status || -101 == e.data.status || -102 == e.data.status) {
            var i = getApp();
            return i.auth.clearAuth(), i.showWarning("正在重新登录", function () {
              var t = getCurrentPages();
              "pages/user/index/index" != t[t.length - 1].route ? wx.navigateTo({
                url: "/pages/user/index/index"
              }) : wx.navigateTo({
                url: "/pages/index/index/index"
              });
            }, null, !0), !1;
          }
          var o = "string" == typeof e.data.msg ? e.data.msg : "数据格式错误";
          return this.showError(o, t), !1;
        }
      }
      "function" == typeof t.success && t.success(e);
    } else "function" == typeof t.success && t.success(e);
  },
  doTimeOut(t, e) {
    if (console.log("app.request", e), "function" == typeof t.fail && 0 == t.fail(e)) return !1;
    this.showError("请求超时", t);
  },
  doFail: function (t, e) {
    if (console.log("app.request", e), "function" == typeof t.fail && 0 == t.fail(e)) return !1;
    this.showError("请求失败", t);
  },
  filterJsonData: function (t) {
    for (var e = t, i = 0; i < t.length && (e = t.substr(i), "{" != t.charAt(i)); i++);
    return e;
  },
  modifyUrl: function (t, e) {
    if (void 0 === e && (e = {}), 0 != t.indexOf("http") && ("string" == typeof e.baseUrl ? t = e.baseUrl + t : void 0 === e.baseUrl && (t = getApp().globalData.setting.url + t)),
      "boolean" == typeof e.notAuthParam && 1 == e.notAuthParam) return t;
    //var i = "is_json=1&unique_id=" + this.getUniqueId() + "&token=" + this.getToken();
    return t += (t.indexOf("?") > 0 ? "&" : "?");// + i;
  },

  modifyUrl2: function (t, e) {
    if (void 0 === e && (e = {}), 0 != t.indexOf("http") && ("string" == typeof e.baseUrl ? t = e.baseUrl + t : void 0 === e.baseUrl && (t = getApp().globalData.setting.hurl + t)),
      "boolean" == typeof e.notAuthParam && 1 == e.notAuthParam) return t;
    //var i = "is_json=1&unique_id=" + this.getUniqueId() + "&token=" + this.getToken();
    return t += (t.indexOf("?") > 0 ? "&" : "?");// + i;
  },


  getToken: function () {
    var t = getApp();
    return null == t.globalData.userInfo ? "" : t.globalData.userInfo.token;
  },
  getUniqueId: function () {
    return this.uniqueId ? this.uniqueId : (this.uniqueId = "miniapp" + t.randomString(17),
      this.uniqueId);
  },
  showLoading: function () {
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
  },
  hideLoading: function () {
    wx.hideLoading();
  },
  showError: function (t, e) {
    wx.showModal({
      title: t,
      showCancel: !1,
      complete: function () {
        1 == e.failRollback && wx.navigateBack();
      }
    });
  },

  request2: function (e, i, o) {
    var n = this, a = o.header ? o.header : {
      "content-type": "application/x-www-form-urlencoded"
    }, s = "GET" != (e = e.toUpperCase()) && o.data ? t.json2Form(o.data) : o.data;
    i = this.modifyUrl2(i, o), o.isShowLoading = void 0 === o.isShowLoading || o.isShowLoading,
      o.isShowLoading && this.showLoading(), console.log("app.request", i, o), wx.request(Object.assign({}, o, {
        url: i,
        method: e,
        data: s,
        header: a,
        success: function (t) {
          o.isShowLoading && n.hideLoading(), n.doSuccess2(o, t);
        },
        fail: function (t) {
          o.isShowLoading && n.hideLoading(), n.doFail(o, t);
        }
      }));
  },
  get2: function (t, e) {
    this.request2("GET", t, e);
  },
  doSuccess2: function (t, e) {
    if (console.log("app.request", e), 1 != t.successReload) {
      if (200 != e.statusCode) return this.showError("请求出错[" + e.statusCode + "]", t),
        !1;
      if (0 != e.data.code) {
        if ("function" == typeof t.failStatus && 0 == t.failStatus(e)) return !1;
        var o = "string" == typeof e.data.msg ? e.data.msg : "数据格式错误";
        return this.showError(o, t), !1;
      }
      "function" == typeof t.success && t.success(e);
    } else "function" == typeof t.success && t.success(e);
  },

  check_timeout(url, delay, func) {
    let now = t.gettimestamp();
    let fail_url = getApp().globalData.fail_url;
    if (fail_url.size > 0) {
      try {
        fail_url.forEach((value, key) => {
          if (value.indexOf(url) > 0 || value === url) {
            if (now - key <= delay) {
              throw new Error('请求超时');
            } else {
              fail_url.delete(key);
            }
          }
        })
      } catch (error) {
        if (error) {
          wx.showModal({
            title: '请求超时',
            showCancel: !1,
          });
          return false;
        }
      }
    }
    typeof func === "function" && func()
  },

  //---promise的使用get----
  promiseGet: function (url, data, delay = 10000) {
    return new Promise((resolve, reject) => {
      this.check_timeout(url, delay, () => {
        var th = this;
        if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
        data.isShowLoading && th.showLoading();
        wx.request({
          url,
          method: 'GET',
          header: { "content-type": "application/x-www-form-urlencoded" },
          data: data.data,
          success(res) {
            data.isShowLoading && th.hideLoading();
            resolve(res);
          },
          fail(err) {
            data.isShowLoading && th.hideLoading();
            if (err && err.errMsg && err.errMsg.indexOf('timeout') != -1) {
              getApp().globalData.fail_url.set(t.gettimestamp(), url);
              console.log('请求超时url---', getApp().globalData.fail_url);
              th.doTimeOut()
            }else{
              reject(err);
            }
          }
        })
      })
    })
  },

  //---promise的使用post----
  promisePost: function (url, data) {
    var th = this;
    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
    var post_data = data.data;
    var header = { "content-type": "application/x-www-form-urlencoded" };
    if (data.is_json) {
      header = { 'content-type': 'application/json' };
      post_data = JSON.stringify(post_data);
    };
    return new Promise((resolve, reject) => {
      data.isShowLoading && th.showLoading();
      wx.request({
        url,
        method: 'POST',
        header: header,
        data: post_data,
        success(res) {
          data.isShowLoading && th.hideLoading();
          resolve(res);
        },
        fail(err) { data.isShowLoading && th.hideLoading(); reject(err); }
      })
    })
  },

  //---promise的使用delete----
  promiseDelete: function (url, data) {
    var th = this;
    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
    return new Promise((resolve, reject) => {
      data.isShowLoading && th.showLoading();
      wx.request({
        url,
        method: 'DELETE',
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: data.data,
        success(res) {
          data.isShowLoading && th.hideLoading();
          resolve(res);
        },
        fail(err) { data.isShowLoading && th.hideLoading(); reject(err); }
      })
    })
  },


  //---promise的使用put----
  promisePut: function (url, data) {
    var th = this;
    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
    var post_data = data.data;
    var header = { "content-type": "application/x-www-form-urlencoded" };
    if (data.is_json) {
      header = { 'content-type': 'application/json' };
      post_data = JSON.stringify(post_data);
    };
    return new Promise((resolve, reject) => {
      data.isShowLoading && th.showLoading();
      wx.request({
        url,
        method: 'PUT',
        header: header,
        data: post_data,
        success(res) {
          data.isShowLoading && th.hideLoading();
          resolve(res);
        },
        fail(err) { data.isShowLoading && th.hideLoading(); reject(err); }
      })
    })
  },

  //--------具有时间限制的读取接口----------
  time_limit_get(time, url, data) {
    var req = this.get(url, data);
    setTimeout(function () {
      if (req) req.abort();
    }, time * 1000)
  },

  /**
   * @param {Object} url    //url地址
   * @param {Object} data   //data入参
   * @param {Object} succ   //成功的回调
   * @param {Object} fail   //失败的回调
   */
  json_post: function (url, data, succ, fail, mathod) {
    var th = this;
    var Mathod = "POST";

    if (mathod) Mathod = mathod;
    this.showLoading();
    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
    var str = JSON.stringify(data);
    wx.request({
      url: url,
      data: str,
      method: Mathod,
      header: {
        'content-type': 'application/json'
      },// 设置请求的 header
      success: function (res) { succ(res); th.hideLoading(); },
      fail: function (res) { fail(res); }
    })
  },

  promise_downimg(url) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: function (res) {
          //res.path是网络图片的本地地址
          resolve(res.path);
        },
        fail: function (err) {
          reject(err);
        }
      });
    })
  }

};