UNPKG

@hopeio/utils

Version:
107 lines (106 loc) 2.85 kB
var l = Object.defineProperty; var I = (u, e, t) => e in u ? l(u, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[e] = t; var a = (u, e, t) => I(u, typeof e != "symbol" ? e + "" : e, t); import m from "qs"; class y { constructor(e) { // 默认的请求配置 a(this, "defaults", { baseUrl: "", header: {}, dataType: "json", // #ifndef MP-WEIXIN responseType: "json", // #endif timeout: 3e4 }); // 请求拦截器 a(this, "requestInterceptors", []); // 响应拦截器 a(this, "responseInterceptors", []); // 响应错误拦截器 a(this, "responseErrorInterceptors", []); a(this, "interceptors", { request: { use: (e) => { this.requestInterceptors.push(e); } }, response: { use: (e, t) => { this.responseInterceptors.push(e), this.responseErrorInterceptors.push(t); } } }); e && (this.defaults = Object.assign(this.defaults, e)); } // 发起请求,默认配置是defaultConfig,也可以传入config参数覆盖掉默认配置中某些属性 request(e, t, s) { return new Promise((h, o) => { if (s != null && s.query) { const r = m.stringify(s.query); t.includes("?") ? t += `&${r}` : t += `?${r}`; } t = ((s == null ? void 0 : s.baseUrl) || this.defaults.baseUrl) + t; const n = s != null && s.header ? Object.assign(this.defaults.header, s.header) : this.defaults.header, i = s != null && s.timeout ? s.timeout : this.defaults.timeout; this.requestInterceptors.length > 0 && !s && (s = {}); for (const r of this.requestInterceptors) s = r(s); let d = { ...s, method: e, url: t, header: n, timeout: i, success: (r) => { let p = { ...r, config: s }; for (const q of this.responseInterceptors) if (!q(p)) { o(p); return; } h(p.data); }, fail: (r) => { for (const p of this.responseErrorInterceptors) if (!p(r)) { o(r); return; } o(r); } }; uni.request(d); }); } // 发起get请求 get(e, t) { return this.request("GET", e, t); } // 发起post请求 post(e, t) { return this.request("POST", e, t); } put(e, t) { return this.request("PUT", e, t); } delete(e, t) { return this.request("DELETE", e, t); } } const b = new y({ header: { "content-type": "application/json" //'user-agent': 'uniapp-' + uni.getAppBaseInfo().appName, }, timeout: 1e4 }); async function U(u, e) { uni.showLoading({ title: u }), await e(), uni.hideLoading(); } export { U as loading, b as unirequest };