UNPKG

wing-axios

Version:
2 lines (1 loc) 1.87 kB
import t from"axios";import e from"qs";function r({baseURL:t="",timeout:e=8e3,withCredentials:r=!1,contentType:n,loadingTips:o={start:()=>{},finish:()=>{},error:()=>{}}}={}){let i={baseURL:t,timeout:e,withCredentials:r};n&&(i.headers={"Content-Type":n}),this.options=i,this.loadingTips=o}function n(t){if(!t)return"";let e=[];for(const r in t)Object.hasOwnProperty.call(t,r)&&e.push(`${r}=${t[r]}`);return e.length>0?"?"+e.join("&"):""}function o(t){return"function"==typeof t}function i(t){return"object"==typeof t}function s({host:t="",baseURL:e="",timeout:s=8e3,withCredentials:a=!0,contentType:u,loadingTips:c={start:()=>{},finish:()=>{},error:()=>{}},apiUrls:p={},token:f,commonParams:l={},commonQuery:h={},onError:m}){let d=new r({baseURL:e,timeout:s,withCredentials:a,contentType:u,loadingTips:c}).create(),y={};for(let e in p){let r=p[e].split(",");const s=r[0]?r[0].toLowerCase():"get";y[e]=(e={},a)=>{let u="";o(h)?u=n(h()):i(h)&&(u=n(h));const c=`${t}${r[1]}${u}`;let p={};o(l)?p=l():i(l)&&(p=l);let y,g={...p,...e};return y="post"===s?a?e:JSON.stringify(g):"put"===s||"patch"===s?JSON.stringify(g):{params:g},f&&("string"==typeof f&&(d.defaults.headers.common.Authorization=`Bearer ${f}`),"function"==typeof f&&(d.defaults.headers.common.Authorization=`Bearer ${f()}`)),d[s](c,y).then((t=>t.data)).catch((t=>m&&m(t)))}}return y}r.prototype.create=function(){let r=t.create(this.options);const{start:n,finish:o,error:i}=this.loadingTips;return r.interceptors.request.use((function(t){const{params:r,data:o,url:i}=t,s=r||e.stringify(o)||{};return t.url=i.replace(/\{\w+\}/gi,(t=>{const e=t.replace(/\{?\}?/gi,"");return s[e]})),n&&n(t),t}),(function(t){return i&&i(t),Promise.reject(t)})),r.interceptors.response.use((function(t){return o&&o(t),t}),(function(t){return i&&i(t),Promise.reject(t)})),r};export{r as WingAxios,s as createWingService,r as default};