UNPKG

wing-axios

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