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

module.exports = {
    uniqueId: "",
    request: function(e, i, o) {
        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 = void 0 === o.isShowLoading || o.isShowLoading, 
        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: function(t) {
                o.isShowLoading && n.hideLoading(), n.doFail(o, t);
            }
        }));
        return req;
    },
  get: function (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);
    },
    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);
  },

  //---promise的使用get----
  promiseGet: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: '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(); reject(err); }
      })
    })
  },

    //---promise的使用get----
    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); }
            })
        })
    },

    //--------具有时间限制的读取接口----------
    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);
				  }
				});
			})
	}

};