axios-sugar
Advanced tools
Comparing version 1.2.0 to 2.0.0-0
@@ -1,1 +0,1 @@ | ||
var AxiosSugar=function(e){"use strict";function i(e){return void 0!==e}var n=function(e){this.isResend=!1,this.resendDelay=1e3,this.resendTimes=3,this.isSave=!1,this.prop="custom",e=e||{};for(var t=0,r=Object.keys(e);t<r.length;t++){var n=r[t];i(this[n])?this[n]=e[n]:console.error("[axios sugar]: the option "+n+" is not valid.")}},o=function(e,t){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function t(e,t){function r(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var r,s={STRING:2,BOOLEAN:4,NUMBER:8},a="undefined"!=typeof window;function u(t){return function(e){if(!a&&r.isBuffer(e))return e.length;switch(typeof e){case"string":return e.length*s.STRING;case"boolean":return s.BOOLEAN;case"number":return s.NUMBER;case"object":return Array.isArray(e)?e.map(u(t)).reduce(function(e,t){return e+t},0):function(e,t){if(null==t)return 0;var r=0;for(var n in t){if("object"==typeof t[n]&&null!==t[n]){if(e.has(t[n]))continue;e.add(t[n])}r+=u(e)(n);try{r+=u(e)(t[n])}catch(e){e instanceof RangeError&&(r=0)}}return r}(t,e);default:return 0}}}function f(e){return u(new WeakSet)(e)}a||(r=require("buffer").Buffer);var c=(p.prototype.set=function(e,t){this.data[e]=t},p.prototype.get=function(e){return this.data[e]||null},p.prototype.contains=function(e){return void 0!==this.data[e]},p);function p(){this.data={}}var l,d=(t(h,l=c),h.prototype.set=function(e,t){for(var r,n,o=this.data,i=0,s=Object.entries(o);i<s.length;i++){var a=s[i],u=a[0],c=a[1];r=(new Date).getTime(),n=c.time,r-n>=this.duration&&delete o[u]}f(t)+f(o)>this.limit&&(o=this.data={}),o[e]={data:t,time:(new Date).getTime()}},h.prototype.get=function(e){var t=this.data[e];return t?t.data:null},h);function h(e,t){var r=l.call(this)||this;return r.duration=3e5,r.limit=15728640,i(e)&&(r.duration=e),i(t)&&(r.limit=t),r}var v=(g.prototype.set=function(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(e){console.error("[axios-sugar]: "+e.message)}},g.prototype.get=function(e){var t=localStorage.getItem(e);return null===t?null:JSON.parse(t)},g.prototype.contains=function(e){return null!==this.get(e)},g);function g(){}var m=(y.prototype.push=function(e){return this.stack.push(e)},y.prototype.pop=function(){return this.stack.pop()},y.prototype.contains=function(e){return 0<=this.stack.indexOf(e)},y.prototype.remove=function(e){return this.stack.splice(this.indexOf(e),1)[0]},y.prototype.indexOf=function(e){return this.stack.indexOf(e)},y);function y(){this.stack=[]}var S,b=(t(O,S=m),O.prototype.forEach=function(n){this.stack.forEach(function(e,t,r){n.call(e,e,t,r)})},O);function O(){return null!==S&&S.apply(this,arguments)||this}var x,R=(t(k,x=m),k);function k(){return null!==x&&x.apply(this,arguments)||this}function w(e){return 0<=["post","put","patch"].indexOf(e)?"data":"get"===e?"params":"both"}function j(e){var t,s=e.url,r=e.method;function n(e){var t="";if(/\?/.test(s)){var r=s.split("?");s=r[0],t+=r[1]}if(e)for(var n=0,o=Object.entries(e);n<o.length;n++){var i=o[n];""!==t&&(t+="&"),t+=i[0]+"="+i[1]}return t}function o(e){return i(e)?JSON.stringify(e):""}switch(w(r)){case"params":t=n(e.params);break;case"data":t=o(e.data);break;case"both":t=n(e.params)||o(e.params)}return"method="+r+"&url="+s+"&data="+t}function P(e,t){return void 0===e?t:e}function A(e,i){var s,t=e.axios,a=e.storage,u=e.config,c=e.lifecycle;t.interceptors.request.use(function(e){if(e=function(e,t){if(void 0===t&&(t="custom"),"data"===w(e.method)&&e.data){var r=e.data[t];r&&(e[t]=r,delete e.data[t])}return e}(e,u.prop),i.contains(e))return s={reason:"existed"},Promise.reject(s);var t=e[u.prop],r=u.isSave;if(t&&(r=P(t.isSave,r)),r){var n=a.get(j(e));if(n)return s={reason:"saved",data:n},Promise.reject(s)}var o=c.beforeRequest(e);return o.state?(i.push(e),Promise.resolve(e)):(s={reason:"beforeRequestBreak",message:o.message},Promise.reject(s))},function(e){Promise.reject(e)})}var N=(T.prototype.beforeRequest=function(e){return{state:!0,message:""}},T.prototype.beforeResponse=function(e){return{state:!0,message:""}},T);function T(){}var E=(B.prototype.init=function(){var e,u,c,f,a,p,l;A(this,this.stack),u=(e=this).stack,f=e.axios,a=e.storage,p=e.config,l=e.lifecycle,f.interceptors.response.use(function(e){var t=e.config,r=e.data,n=l.beforeResponse(e);if(!n.state)return c={reason:"beforeResponseBreak",message:n.message},Promise.reject(c);t&&u.remove(t);var o,i=t.custom;if(i&&(o=P(i.isSave,p.isSave)),o){var s=j(t);a.set(s,r)}return Promise.resolve(r)},function(e){var t=e.reason;if(t)return"saved"===t?Promise.resolve(e.data):Promise.reject(e);var r=e.config;if(r){u.remove(r);var n=r[p.prop],o=p.isResend,i=p.resendDelay,s=p.resendTimes,a=0;return n&&(o=P(n.isResend,o),i=P(n.resendDelay,i),s=P(n.resendTimes,s),a=P(n.curResendTimes,0)),o?a<s?new Promise(function(e){setTimeout(function(){return n||(r.custom={}),r.custom.curResendTimes=++a,"string"==typeof r.data&&(r.data=JSON.parse(r.data)),e(f.request(r))},i)}):(c={reason:"resendEnd",message:"Can't get a response."},Promise.reject(c)):Promise.reject(e)}})},B);function B(e,t){var r=this;void 0===t&&(t={}),this.stack=new b,this.config=new n,this.storage=new c,this.lifecycle=new N,this.axios=e,["config","storage","lifecycle"].forEach(function(e){t[e]&&(r[e]=t[e])}),this.init()}var _=new R;return e.AxiosSugarConfig=n,e.AxiosSugarInnerReleaseStorage=d,e.AxiosSugarInnerStorage=c,e.AxiosSugarLifeCycle=N,e.AxiosSugarLocalStorage=v,e.default=function(e,t){if(void 0===t&&(t={}),!_.contains(e))return _.push(e),new E(e,t);console.error("[axios-sugar]: an axios static or instance only can call factory once.")},e}({}); | ||
var AxiosSugar=function(e,a){"use strict";a=a&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a;var r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function t(e,t){function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function c(n,r){var o,i,a,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},e={next:t(0),throw:t(1),return:t(2)};return"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function(t){if(o)throw new TypeError("Generator is already executing.");for(;s;)try{if(o=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,a&&(t=[2&t[0],a.value]),t[0]){case 0:case 1:a=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,i=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(a=0<(a=s.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3])){s.label=t[1];break}if(6===t[0]&&s.label<a[1]){s.label=a[1],a=t;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(t);break}a[2]&&s.ops.pop(),s.trys.pop();continue}t=r.call(n,s)}catch(e){t=[6,e],i=0}finally{o=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,e])}}}function s(e,t){var n;if(null!=e)if("object"!=typeof e&&(e=[e]),n=e,"[object Array]"===toString.call(n))for(var r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}function o(e){return void 0!==e}function n(e){return"[axios-sugar]: "+e+"."}function l(e){console.warn(n(e))}function f(e){console.error(n(e))}function u(e){throw new Error(n(e))}function p(){return"development"===process.env.NODE_ENV}function h(e){return"function"==typeof e}function d(e){return"number"==typeof e}function g(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function n(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={};function o(e,t){"object"==typeof r[t]&&"object"==typeof e?r[t]=n(r[t],e):r[t]="object"==typeof e?n({},e):e}for(var i=0,a=arguments.length;i<a;i++)s(e[i],o);return r}.apply(null,e)}function i(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function n(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={};function o(e,t){"object"==typeof r[t]&&"object"==typeof e?r[t]=n(r[t],e):r[t]=e}for(var i=0,a=arguments.length;i<a;i++)s(e[i],o);return r}.apply(null,e)}var v,y={STRING:2,BOOLEAN:4,NUMBER:8},m="undefined"!=typeof window;function b(t){return function(e){if(!m&&v.isBuffer(e))return e.length;switch(typeof e){case"string":return e.length*y.STRING;case"boolean":return y.BOOLEAN;case"number":return y.NUMBER;case"object":return Array.isArray(e)?e.map(b(t)).reduce(function(e,t){return e+t},0):function(e,t){if(null==t)return 0;var n=0;for(var r in t){if("object"==typeof t[r]&&null!==t[r]){if(e.has(t[r]))continue;e.add(t[r])}n+=b(e)(r);try{n+=b(e)(t[r])}catch(e){e instanceof RangeError&&(n=0)}}return n}(t,e);default:return 0}}}function T(e){return b(new WeakSet)(e)}m||(v=require("buffer").Buffer);var w={release:!1,duration:3e5,limit:15728640},x=(S.prototype.release=function(e,t){var n;this.config.release&&o(this.data[e])&&(this.config.duration?(n=this.data[e].time,(new Date).getTime()-n>=this.config.duration&&(this.data[e]=void 0)):o(t)&&T(this.data)+T(t)>this.config.limit&&h(this.full)&&this.full(e,t))},S.prototype.full=function(e,t){u("The capacity of the storage is full")},S.prototype.set=function(e,t){try{return this.release(e,t),this.data[e]=t,!0}catch(e){return p()&&f(e.message),!1}},S.prototype.get=function(e){return this.release(e),this.data[e]||null},S);function S(e){this.data={},this.config=e?i(w,e):w}var O=(E.prototype.set=function(e,t){try{return localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){return p()&&f(e.message),!1}},E.prototype.get=function(e){var t=localStorage.getItem(e);return null===t?null:JSON.parse(t)},E);function E(){this.data={}}var j={repeat:{interval:2e3},onlineCheck:{enable:!1,reconnect:{enable:!0}},save:{enable:!1,storage:new x},retry:{enable:!1,auto:!0,count:3,delay:2e3}},P=(A.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},A.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},A.prototype.each=function(t){this.handlers.forEach(function(e){null!==e&&t(e)})},A);function A(){this.handlers=[]}var N={tags:[],cancels:[],configs:[]};function _(e){(N.configs[e]=null)!==N.tags[e]&&(N.tags[e]=null,N.cancels[e]=null)}var k,q={get:function(e){var t=e.sugar.save;if(t.enable){var n=t.storage,r=N.tags[e.index];if(null!==r)return n.get(r)}return null},set:function(e){var t=e.sugar.save;if(t.enable){var n=t.storage,r=N.tags[e.index];if(null!==r)return n.set(r,{response:e.response,time:(new Date).getTime()}),!0}return!1}},B=(t(D,k=Error),D);function D(e,t){var n=this.constructor,r=k.call(this,e.message)||this;return r.name=n.name,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r,n),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(r,n.prototype):r.__proto__=n.prototype,r.reason=e,r.axios=t.axios,r.index=t.index,r.sugar=t.sugar,r.count=t.count,r.sendingTime=t.sendingTime,r.completeTime=t.completeTime,r.isAxiosSugarError=!0,r}function C(e){return e?JSON.stringify(e):""}function R(e,t,n){return t-e<n}function F(e,t){return function(e){var t,n,r,o=e.url,i=e.method;switch(0<=["post","put","patch"].indexOf(i)?"data":"params"){case"params":t=e.params||{},"get"===i&&(t=g((r={},0<=(n=o).indexOf("?")&&n.trim().substring(n.indexOf()).split("&").forEach(function(e){var t=e.trim().split("=");1===t.length?r[t[0]]="":r[t[0]]=r[t[1]]}),r),t)),t=C(t);break;case"data":t=C(e.data)}return"method="+i+"&url="+o+"&data="+t}(e)}function I(t){var n=this,e=re.repeatTag(t.axios,t.sugar),r=N.tags.indexOf(e);0<=r&&N.configs[r].sendingTime&&!R(N.configs[r].sendingTime,(new Date).getTime(),t.sugar.repeat.interval)&&(_(r),r=-1);function o(){var e=n.events.repeated;h(e)&&e.call(n,t)}0<=r&&(N.configs[r]&&N.configs[r].completeTime?(o(),u("The current request is repeated.")):(N.cancels[r]("The previous request is repeated."),N.tags[r]=null,N.cancels[r]=null,o()));var i=a.CancelToken.source();return t.axios.cancelToken=i.token,N.cancels.push(i.cancel),N.tags.push(e)-1}var X,U=(t(G,X=Error),G);function G(e){var t=this.constructor,n=X.call(this,e.message)||this;return n.name=t.name,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(n,t),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(n,t.prototype):n.__proto__=t.prototype,n.reason=e,n}function L(e){return o(e)?e instanceof Promise?"promise":e instanceof Error?o(e.reason)?"reasonError":"error":void 0:"undefined"}function M(e){switch(L(e)){case"undefined":return;case"error":return new U(e);default:return e}}var J=function(e){var t=M(e);return t instanceof Promise?t.then(M,M):t};var z=(H.prototype.setStatusHandler=function(e,t){return this.reservedCodes.indexOf(e)<0?(this.statusTable[e]=t,!0):(p()&&f("can't set the handler of http status code "+e+"."),!1)},H.prototype.dispatch=function(n,r,o){var e=r.toString().substr(0,1),t=o.response,i=!1,a=void 0,s=o.reason&&o.sugar.retry.enable?function(){return i?(p()&&l("retry has been already called"),!1):(i=!0,a=function(n){var r=this;if(d(n.count)?n.count+=1:n.count=1,d(n.sugar.retry.count)&&n.count<=n.sugar.retry.count){var e=r.events.retried;return e&&e.call(r,n),new Promise(function(e,t){setTimeout(function(){t(r.request(n))},n.sugar.retry.delay)})}var t=r.events.retryFailed;return h(t)&&t.call(r,n),new Error("[axios-sugar]: retryFiled.")}.call(n,o),!0)}:void 0;function u(e,t){return e.call(n,r,o,t,s)}return h(this["on"+e+"XXBefore"])?t=u(this["on"+e+"XXBefore"],t):h(this.onStatusBefore)&&(t=u(this.onStatusBefore,t)),h(this.statusTable[r])&&(t=u(this.statusTable[r],t)),h(this["on"+e+"XXAfter"])?t=u(this["on"+e+"XXAfter"],t):h(this.onStatusAfter)&&(t=u(this.onStatusAfter,t)),a||t},H);function H(){this.statusTable={400:this.onBadRequest,401:this.onUnauthorized,403:this.onForbidden,404:this.onNotFound,405:this.onMethodNotAllow,406:this.onNotAcceptable,407:this.onProxyAuthenticationRequired,408:this.onTimeout,409:this.onConflict,500:this.onInternalServerError,501:this.onNotImplemented,502:this.onBadGateway},this.reservedCodes=Object.keys(this.statusTable)}var V,W=(t(K,V=z),K);function K(){return null!==V&&V.apply(this,arguments)||this}function Q(e,t,n){n&&t.sugar.retry.auto&&(n()||l("retry has been already retried before"))}function Y(e,t){var n=g(e,t);return t.save&&t.save.storage?n.save.storage=t.save.storage:n.save.storage=e.save.storage,n}["BadRequest","Unauthorized","Forbidden","NotFound","MethodNotAllow","NotAcceptable","ProxyAuthenticationRequired","Conflict","InternalServerError","NotImplemented","BadGateway"].forEach(function(e){W.prototype["on"+e]=function(e,t,n,r){return p()&&f(t.reason.message),Q(0,t,r),t.reason}}),W.prototype.on=function(e,t){var n;this["on"+((n=e).substring(0,1).toUpperCase()+n.substring(1))]=t},W.prototype.onTimeout=function(e,r,t,o){return i=this,u=function(){var t,n=this;return c(this,function(e){return(t=r.sugar.onlineCheck).enable?navigator.onLine?(p()&&f("online but timeout"),h(this.events.onlineTimeout)&&this.events.onlineTimeout.call(this,r,o),Q(0,r,o)):(p()&&f("offline"),h(this.events.offline)&&this.events.offline.call(this,r),t.reconnect.enable&&window.addEventListener("online",function(){h(n.events.online)&&(n.events.online.call(n,r,o),Q(0,r,o))})):(p()&&f(r.reason.message),Q(0,r,o)),[2,r.reason]})},new(s=(s=a=void 0)||Promise)(function(e,t){function n(e){try{o(u.next(e))}catch(e){t(e)}}function r(e){try{o(u.throw(e))}catch(e){t(e)}}function o(t){t.done?e(t.value):new s(function(e){e(t.value)}).then(n,r)}o((u=u.apply(i,a||[])).next())});var i,a,s,u};var Z,$=new W,ee=(te.prototype.request=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r;r=(r="string"==typeof t[0]?((e=t[1]||{}).url=t[0],t[2]):(e=t[0]||{},t[1]))?Y(j,r):this.config;var o=[function(n){var e=n.sugar.save.enable?q.get(n):null;return n.sendingTime=(new Date).getTime(),null!==e?Promise.resolve({response:e.response,sugar:n.sugar,index:n.index,sendingTime:n.sendingTime,cacheTime:e.time,completeTime:(new Date).getTime()}):this.axios.request(n.axios).then(function(e){return n.completeTime=(new Date).getTime(),{response:e,sugar:n.sugar,index:n.index,sendingTime:n.sendingTime,completeTime:n.completeTime}},function(e){n.completeTime=(new Date).getTime();var t=new B(e,n);return Promise.reject(t)})}.bind(this),void 0],i=e,a=i.isAxiosSugarError?{axios:i.axios,sugar:i.sugar,count:(d(i.count),i.count)}:{axios:e,sugar:r,cancelDisabled:!1},s=Promise.resolve(a);for(this.interceptors.request.each(function(e){o.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.each(function(e){o.push(e.fulfilled,e.rejected)});o.length;)s=s.then(o.shift(),o.shift());return s},te.prototype.on=function(e,t){this.events[e]=t},te.prototype.off=function(e,t){return this.events[e]===t&&!(this.events[e]=void 0)},te);function te(e,t){var n;this.httpStatusProcessor=$,this.axios=a.create(e),this.config=t||Object.assign({},j),this.events={},this.interceptors={request:new P,response:new P},(n=this).interceptors.request.use(function(e){return N.configs.push(e),e.index=I.call(n,e),e},function(e){return Promise.reject(e)}),n.interceptors.response.use(function(e){var t;return!q.set(e)||h(t=n.events.stored)&&t.call(n,e),R(e.sendingTime,e.completeTime,e.sugar.repeat.interval)||_(e.index),n.httpStatusProcessor.dispatch(n,e.response.status.toString(),e)},function(e){var t=e;return e.reason&&!R(e.sendingTime,e.completeTime,e.sugar.repeat.interval)&&_(e.index),e.reason&&e.reason.response&&(t=n.httpStatusProcessor.dispatch(n,e.reason.response.status.toString(),e)),(t=J(t))instanceof Promise&&1<=e.count&&_(e.index),t instanceof Promise?t:Promise.reject(t||e)})}function ne(){var e=Z.call(this)||this;return e.repeatTag=F,e.defaults=j,e.axiosDefaults=a.defaults,e.axios=a,e}["delete","get","head","options"].forEach(function(r){ee.prototype[r]=function(e,t,n){return this.request(i(t||{},{method:r,url:e}),n)}}),["post","put","patch"].forEach(function(o){ee.prototype[o]=function(e,t,n,r){return this.request(i(n||{},{method:o,url:e,data:t}),r)}});var re=new(t(ne,Z=ee),ne.prototype.create=function(e,t){return t=t&&Y(j,t),new ee(e,t)},ne.prototype.isCancel=function(e){return!!e.reason&&a.isCancel(e.reason)},ne.prototype.getUri=function(e){return a.getUri(e)},ne.prototype.spread=function(e){return a.spread(e)},ne.prototype.all=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return a.all(e)},ne.prototype.cancelAll=function(){var t=[];N.configs.map(function(e){null!==e&&t.push({cancel:N.cancels[e.index],config:e})}),h(this.cancelFilter)&&(t=this.cancelFilter(t)),t.forEach(function(e){e.cancel()})},ne.prototype.cancelFilter=function(e){return e.filter(function(e){return!e.config.cancelDisabled})},ne.prototype.cancelAutoRetry=function(e){e.sugar.retry.auto=!1},ne),oe={inner:x,local:O};return e.AxiosSugar=ee,e.HttpStatusProcessor=W,e.default=re,e.storage=oe,e}({},axios); |
@@ -5,32 +5,5 @@ 'use strict'; | ||
function isDef(value) { | ||
return typeof value !== 'undefined'; | ||
} | ||
function isStr(value) { | ||
return typeof value === 'string'; | ||
} | ||
function getDurationMS(a, b) { | ||
return a - b; | ||
} | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
var AxiosSugarConfig = (function () { | ||
function AxiosSugarConfig(options) { | ||
this.isResend = false; | ||
this.resendDelay = 1000; | ||
this.resendTimes = 3; | ||
this.isSave = false; | ||
this.prop = 'custom'; | ||
options = options || {}; | ||
for (var _i = 0, _a = Object.keys(options); _i < _a.length; _i++) { | ||
var key = _a[_i]; | ||
if (isDef(this[key])) { | ||
this[key] = options[key]; | ||
} | ||
else { | ||
console.error("[axios sugar]: the option " + key + " is not valid."); | ||
} | ||
} | ||
} | ||
return AxiosSugarConfig; | ||
}()); | ||
var axios = _interopDefault(require('axios')); | ||
@@ -66,2 +39,158 @@ /*! ***************************************************************************** | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
function __generator(thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
} | ||
function isArray(val) { | ||
return toString.call(val) === '[object Array]'; | ||
} | ||
function forEach(obj, fn) { | ||
if (obj === null || typeof obj === 'undefined') { | ||
return; | ||
} | ||
if (typeof obj !== 'object') { | ||
obj = [obj]; | ||
} | ||
if (isArray(obj)) { | ||
for (var i = 0, l = obj.length; i < l; i++) { | ||
fn.call(null, obj[i], i, obj); | ||
} | ||
} | ||
else { | ||
for (var key in obj) { | ||
if (Object.prototype.hasOwnProperty.call(obj, key)) { | ||
fn.call(null, obj[key], key, obj); | ||
} | ||
} | ||
} | ||
} | ||
function merge() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var result = {}; | ||
function assignValue(val, key) { | ||
if (typeof result[key] === 'object' && typeof val === 'object') { | ||
result[key] = merge(result[key], val); | ||
} | ||
else { | ||
result[key] = val; | ||
} | ||
} | ||
for (var i = 0, l = arguments.length; i < l; i++) { | ||
forEach(args[i], assignValue); | ||
} | ||
return result; | ||
} | ||
function deepMerge() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var result = {}; | ||
function assignValue(val, key) { | ||
if (typeof result[key] === 'object' && typeof val === 'object') { | ||
result[key] = deepMerge(result[key], val); | ||
} | ||
else if (typeof val === 'object') { | ||
result[key] = deepMerge({}, val); | ||
} | ||
else { | ||
result[key] = val; | ||
} | ||
} | ||
for (var i = 0, l = arguments.length; i < l; i++) { | ||
forEach(args[i], assignValue); | ||
} | ||
return result; | ||
} | ||
function capitalize(str) { | ||
return str.substring(0, 1).toUpperCase() + str.substring(1); | ||
} | ||
function isDef(value) { | ||
return typeof value !== 'undefined'; | ||
} | ||
function isStr(value) { | ||
return typeof value === 'string'; | ||
} | ||
function isError(value) { | ||
return value instanceof Error; | ||
} | ||
function getDurationMS(a, b) { | ||
return a - b; | ||
} | ||
function customMessage(msg) { | ||
return "[axios-sugar]: " + msg + "."; | ||
} | ||
function warn(msg) { | ||
console.warn(customMessage(msg)); | ||
} | ||
function error(msg) { | ||
console.error(customMessage(msg)); | ||
} | ||
function throwError(msg) { | ||
throw new Error(customMessage(msg)); | ||
} | ||
function isDev() { | ||
return process.env.NODE_ENV === 'development'; | ||
} | ||
function isFn(val) { | ||
return typeof val === 'function'; | ||
} | ||
function isNum(val) { | ||
return typeof val === 'number'; | ||
} | ||
function deepMerge$1() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return deepMerge.apply(null, args); | ||
} | ||
function merge$1() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return merge.apply(null, args); | ||
} | ||
function isOnline(options) { | ||
return navigator.onLine; | ||
} | ||
var ECMA_SIZES = { | ||
@@ -133,128 +262,245 @@ STRING: 2, | ||
var innerStorageDefaults = { | ||
release: false, | ||
duration: 5 * 60 * 1000, | ||
limit: 15 * 1024 * 1024 | ||
}; | ||
var AxiosSugarInnerStorage = (function () { | ||
function AxiosSugarInnerStorage() { | ||
function AxiosSugarInnerStorage(config) { | ||
this.data = {}; | ||
this.config = config ? merge$1(innerStorageDefaults, config) : innerStorageDefaults; | ||
} | ||
AxiosSugarInnerStorage.prototype.set = function (symbol, res) { | ||
this.data[symbol] = res; | ||
AxiosSugarInnerStorage.prototype.release = function (tag, data) { | ||
if (this.config.release && isDef(this.data[tag])) { | ||
if (this.config.duration) { | ||
var time = this.data[tag].time; | ||
if (getDurationMS(new Date().getTime(), time) >= this.config.duration) { | ||
this.data[tag] = undefined; | ||
} | ||
} | ||
else if (isDef(data) && | ||
sizeof(this.data) + sizeof(data) > this.config.limit) { | ||
if (isFn(this.full)) { | ||
this.full(tag, data); | ||
} | ||
} | ||
} | ||
}; | ||
AxiosSugarInnerStorage.prototype.get = function (symbol) { | ||
return this.data[symbol] || null; | ||
AxiosSugarInnerStorage.prototype.full = function (tag, data) { | ||
throwError('The capacity of the storage is full'); | ||
}; | ||
AxiosSugarInnerStorage.prototype.contains = function (symbol) { | ||
return typeof this.data[symbol] !== 'undefined'; | ||
}; | ||
return AxiosSugarInnerStorage; | ||
}()); | ||
var AxiosSugarInnerReleaseStorage = (function (_super) { | ||
__extends(AxiosSugarInnerReleaseStorage, _super); | ||
function AxiosSugarInnerReleaseStorage(duration, limit) { | ||
var _this = _super.call(this) || this; | ||
_this.duration = 5 * 60 * 1000; | ||
_this.limit = 15 * 1024 * 1024; | ||
if (isDef(duration)) | ||
_this.duration = duration; | ||
if (isDef(limit)) | ||
_this.limit = limit; | ||
return _this; | ||
} | ||
AxiosSugarInnerReleaseStorage.prototype.set = function (symbol, res) { | ||
var data = this.data; | ||
for (var _i = 0, _a = Object.entries(data); _i < _a.length; _i++) { | ||
var _b = _a[_i], key = _b[0], item = _b[1]; | ||
if (getDurationMS(new Date().getTime(), item.time) >= this.duration) { | ||
delete data[key]; | ||
AxiosSugarInnerStorage.prototype.set = function (tag, data) { | ||
try { | ||
this.release(tag, data); | ||
this.data[tag] = data; | ||
return true; | ||
} | ||
catch (err) { | ||
if (isDev()) { | ||
error(err.message); | ||
} | ||
return false; | ||
} | ||
if (sizeof(res) + sizeof(data) > this.limit) { | ||
data = this.data = {}; | ||
} | ||
data[symbol] = { | ||
data: res, | ||
time: new Date().getTime() | ||
}; | ||
}; | ||
AxiosSugarInnerReleaseStorage.prototype.get = function (symbol) { | ||
var target = this.data[symbol]; | ||
return target ? target.data : null; | ||
AxiosSugarInnerStorage.prototype.get = function (tag) { | ||
this.release(tag); | ||
return this.data[tag] || null; | ||
}; | ||
return AxiosSugarInnerReleaseStorage; | ||
}(AxiosSugarInnerStorage)); | ||
return AxiosSugarInnerStorage; | ||
}()); | ||
var AxiosSugarLocalStorage = (function () { | ||
function AxiosSugarLocalStorage() { | ||
this.data = {}; | ||
} | ||
AxiosSugarLocalStorage.prototype.set = function (symbol, res) { | ||
AxiosSugarLocalStorage.prototype.set = function (tag, data) { | ||
try { | ||
localStorage.setItem(symbol, JSON.stringify(res)); | ||
localStorage.setItem(tag, JSON.stringify(data)); | ||
return true; | ||
} | ||
catch (err) { | ||
console.error("[axios-sugar]: " + err.message); | ||
if (isDev()) { | ||
error(err.message); | ||
} | ||
return false; | ||
} | ||
}; | ||
AxiosSugarLocalStorage.prototype.get = function (symbol) { | ||
var data = localStorage.getItem(symbol); | ||
AxiosSugarLocalStorage.prototype.get = function (tag) { | ||
var data = localStorage.getItem(tag); | ||
return data === null ? null : JSON.parse(data); | ||
}; | ||
AxiosSugarLocalStorage.prototype.contains = function (symbol) { | ||
return this.get(symbol) !== null; | ||
}; | ||
return AxiosSugarLocalStorage; | ||
}()); | ||
var Stack = (function () { | ||
function Stack() { | ||
this.stack = []; | ||
var defaults = { | ||
repeat: { | ||
interval: 2000 | ||
}, | ||
onlineCheck: { | ||
enable: false, | ||
reconnect: { | ||
enable: true | ||
} | ||
}, | ||
save: { | ||
enable: false, | ||
storage: new AxiosSugarInnerStorage() | ||
}, | ||
retry: { | ||
enable: false, | ||
auto: true, | ||
count: 3, | ||
delay: 2000 | ||
} | ||
Stack.prototype.push = function (el) { | ||
return this.stack.push(el); | ||
}; | ||
var AxiosSugarInterceptorManager = (function () { | ||
function AxiosSugarInterceptorManager() { | ||
this.handlers = []; | ||
} | ||
AxiosSugarInterceptorManager.prototype.use = function (fulfilled, rejected) { | ||
this.handlers.push({ | ||
fulfilled: fulfilled, | ||
rejected: rejected | ||
}); | ||
return this.handlers.length - 1; | ||
}; | ||
Stack.prototype.pop = function () { | ||
return this.stack.pop(); | ||
AxiosSugarInterceptorManager.prototype.eject = function (i) { | ||
if (this.handlers[i]) { | ||
this.handlers[i] = null; | ||
} | ||
}; | ||
Stack.prototype.contains = function (el) { | ||
return this.stack.indexOf(el) >= 0; | ||
AxiosSugarInterceptorManager.prototype.each = function (fn) { | ||
this.handlers.forEach(function (handler) { | ||
if (handler !== null) { | ||
fn(handler); | ||
} | ||
}); | ||
}; | ||
Stack.prototype.remove = function (el) { | ||
return this.stack.splice(this.indexOf(el), 1)[0]; | ||
}; | ||
Stack.prototype.indexOf = function (el) { | ||
return this.stack.indexOf(el); | ||
}; | ||
return Stack; | ||
return AxiosSugarInterceptorManager; | ||
}()); | ||
var AxiosSugarRequestStack = (function (_super) { | ||
__extends(AxiosSugarRequestStack, _super); | ||
function AxiosSugarRequestStack() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
var middleData = { | ||
tags: [], | ||
cancels: [], | ||
configs: [] | ||
}; | ||
function dataDestory(index) { | ||
middleData.configs[index] = null; | ||
if (middleData.tags[index] !== null) { | ||
middleData.tags[index] = null; | ||
middleData.cancels[index] = null; | ||
} | ||
AxiosSugarRequestStack.prototype.forEach = function (cb) { | ||
this.stack.forEach(function (conf, confIdx, thisArg) { | ||
cb.call(conf, conf, confIdx, thisArg); | ||
} | ||
var storage = { | ||
get: function (config) { | ||
var save = config.sugar.save; | ||
if (save.enable) { | ||
var storage = save.storage; | ||
var tag = middleData.tags[config.index]; | ||
if (tag !== null) { | ||
return storage.get(tag); | ||
} | ||
} | ||
return null; | ||
}, | ||
set: function (config) { | ||
var save = config.sugar.save; | ||
if (save.enable) { | ||
var storage = save.storage; | ||
var tag = middleData.tags[config.index]; | ||
if (tag !== null) { | ||
storage.set(tag, { | ||
response: config.response, | ||
time: new Date().getTime() | ||
}); | ||
return true; | ||
} | ||
} | ||
return false; | ||
} | ||
}; | ||
var MiddleResponseError = (function (_super) { | ||
__extends(MiddleResponseError, _super); | ||
function MiddleResponseError(reason, config) { | ||
var _newTarget = this.constructor; | ||
var _this = _super.call(this, reason.message) || this; | ||
_this.name = _newTarget.name; | ||
if (typeof Error.captureStackTrace === 'function') { | ||
Error.captureStackTrace(_this, (_newTarget)); | ||
} | ||
if (typeof Object.setPrototypeOf === 'function') { | ||
Object.setPrototypeOf(_this, _newTarget.prototype); | ||
} | ||
else { | ||
_this.__proto__ = _newTarget.prototype; | ||
} | ||
_this.reason = reason; | ||
_this.axios = config.axios; | ||
_this.index = config.index; | ||
_this.sugar = config.sugar; | ||
_this.count = config.count; | ||
_this.sendingTime = config.sendingTime; | ||
_this.completeTime = config.completeTime; | ||
_this.isAxiosSugarError = true; | ||
return _this; | ||
} | ||
return MiddleResponseError; | ||
}(Error)); | ||
function dispatchRequest (config) { | ||
var cache = config.sugar.save.enable ? storage.get(config) : null; | ||
config.sendingTime = new Date().getTime(); | ||
if (cache !== null) { | ||
return Promise.resolve({ | ||
response: cache.response, | ||
sugar: config.sugar, | ||
index: config.index, | ||
sendingTime: config.sendingTime, | ||
cacheTime: cache.time, | ||
completeTime: new Date().getTime() | ||
}); | ||
}; | ||
return AxiosSugarRequestStack; | ||
}(Stack)); | ||
var AxiosStack = (function (_super) { | ||
__extends(AxiosStack, _super); | ||
function AxiosStack() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
return AxiosStack; | ||
}(Stack)); | ||
else { | ||
return this.axios.request(config.axios).then(function (response) { | ||
config.completeTime = new Date().getTime(); | ||
return { | ||
response: response, | ||
sugar: config.sugar, | ||
index: config.index, | ||
sendingTime: config.sendingTime, | ||
completeTime: config.completeTime | ||
}; | ||
}, function (reason) { | ||
config.completeTime = new Date().getTime(); | ||
var error = new MiddleResponseError(reason, config); | ||
return Promise.reject(error); | ||
}); | ||
} | ||
} | ||
function sendDataWay(method) { | ||
var isInData = ['post', 'put', 'patch'].indexOf(method) >= 0, isInParams = method === 'get'; | ||
return isInData ? 'data' : (isInParams ? 'params' : 'both'); | ||
var isInData = ['post', 'put', 'patch'].indexOf(method) >= 0; | ||
return isInData ? 'data' : 'params'; | ||
} | ||
function normalizeProp(config, prop) { | ||
if (prop === void 0) { prop = 'custom'; } | ||
if (sendDataWay(config.method) === 'data' && config.data) { | ||
var propVal = config.data[prop]; | ||
if (propVal) { | ||
config[prop] = propVal; | ||
delete config.data[prop]; | ||
} | ||
function querystring(url) { | ||
var result = {}; | ||
var index = url.indexOf('?'); | ||
if (index >= 0) { | ||
var arr = url.trim().substring(url.indexOf()).split('&'); | ||
arr.forEach(function (item) { | ||
var arr = item.trim().split('='); | ||
if (arr.length === 1) { | ||
result[arr[0]] = ''; | ||
} | ||
else { | ||
result[arr[0]] = result[arr[1]]; | ||
} | ||
}); | ||
} | ||
return config; | ||
return result; | ||
} | ||
function getDataString(data) { | ||
return data ? JSON.stringify(data) : ''; | ||
} | ||
function genSymbol(config) { | ||
@@ -264,201 +510,492 @@ var url = config.url; | ||
var data; | ||
function getParamsSymbolData(params) { | ||
var data = ''; | ||
if (/\?/.test(url)) { | ||
var part = url.split('?'); | ||
url = part[0]; | ||
data += part[1]; | ||
} | ||
if (params) { | ||
for (var _i = 0, _a = Object.entries(params); _i < _a.length; _i++) { | ||
var _b = _a[_i], key = _b[0], val = _b[1]; | ||
if (data !== '') | ||
data += '&'; | ||
data += key + "=" + val; | ||
switch (sendDataWay(method)) { | ||
case 'params': { | ||
data = config.params || {}; | ||
if (method === 'get') { | ||
data = deepMerge$1(querystring(url), data); | ||
} | ||
data = getDataString(data); | ||
break; | ||
} | ||
return data; | ||
case 'data': data = getDataString(config.data); | ||
} | ||
function getDataSymbolData(data) { | ||
return isDef(data) ? JSON.stringify(data) : ''; | ||
return "method=" + method + "&url=" + url + "&data=" + data; | ||
} | ||
function isInInterval(sendingTime, completeTime, interval) { | ||
return getDurationMS(completeTime, sendingTime) < interval; | ||
} | ||
function repeatTag(axiosConfig, config) { | ||
return genSymbol(axiosConfig); | ||
} | ||
function repeat (config) { | ||
var _this = this; | ||
var tag = SugarStatic.repeatTag(config.axios, config.sugar); | ||
var i = middleData.tags.indexOf(tag); | ||
if (i >= 0 && | ||
middleData.configs[i].sendingTime && | ||
!isInInterval(middleData.configs[i].sendingTime, new Date().getTime(), config.sugar.repeat.interval)) { | ||
dataDestory(i); | ||
i = -1; | ||
} | ||
switch (sendDataWay(method)) { | ||
case 'params': | ||
data = getParamsSymbolData(config.params); | ||
break; | ||
case 'data': | ||
data = getDataSymbolData(config.data); | ||
break; | ||
case 'both': | ||
data = getParamsSymbolData(config.params) || getDataSymbolData(config.params); | ||
var callRepeated = function () { | ||
var repeated = _this.events['repeated']; | ||
if (isFn(repeated)) { | ||
repeated.call(_this, config); | ||
} | ||
}; | ||
if (i >= 0) { | ||
if (middleData.configs[i] && middleData.configs[i].completeTime) { | ||
callRepeated(); | ||
throwError('The current request is repeated.'); | ||
} | ||
else { | ||
middleData.cancels[i]('The previous request is repeated.'); | ||
middleData.tags[i] = null; | ||
middleData.cancels[i] = null; | ||
callRepeated(); | ||
} | ||
} | ||
return "method=" + method + "&url=" + url + "&data=" + data; | ||
var source = axios.CancelToken.source(); | ||
config.axios.cancelToken = source.token; | ||
middleData.cancels.push(source.cancel); | ||
return middleData.tags.push(tag) - 1; | ||
} | ||
function notUndef(targetVal, defaultVal) { | ||
return typeof targetVal === 'undefined' ? defaultVal : targetVal; | ||
} | ||
function responseInterceptors (sugar, stack) { | ||
var axios = sugar.axios; | ||
var storage = sugar.storage; | ||
var conf = sugar.config; | ||
var lifecycle = sugar.lifecycle; | ||
var error; | ||
axios.interceptors.response.use(function (res) { | ||
var config = res.config; | ||
var resData = res.data; | ||
var cycleRes = lifecycle.beforeResponse(res); | ||
if (!cycleRes.state) { | ||
error = { reason: 'beforeResponseBreak', message: cycleRes.message }; | ||
return Promise.reject(error); | ||
var ReasonError = (function (_super) { | ||
__extends(ReasonError, _super); | ||
function ReasonError(error) { | ||
var _newTarget = this.constructor; | ||
var _this = _super.call(this, error.message) || this; | ||
_this.name = _newTarget.name; | ||
if (typeof Error.captureStackTrace === 'function') { | ||
Error.captureStackTrace(_this, (_newTarget)); | ||
} | ||
if (config) { | ||
stack.remove(config); | ||
if (typeof Object.setPrototypeOf === 'function') { | ||
Object.setPrototypeOf(_this, _newTarget.prototype); | ||
} | ||
var custom = config.custom; | ||
var isSave; | ||
if (custom) { | ||
isSave = notUndef(custom.isSave, conf.isSave); | ||
else { | ||
_this.__proto__ = _newTarget.prototype; | ||
} | ||
if (isSave) { | ||
var symbol = genSymbol(config); | ||
storage.set(symbol, resData); | ||
_this.reason = error; | ||
return _this; | ||
} | ||
return ReasonError; | ||
}(Error)); | ||
function dataType(data) { | ||
if (isDef(data)) { | ||
if (data instanceof Promise) { | ||
return 'promise'; | ||
} | ||
return Promise.resolve(resData); | ||
}, function (err) { | ||
var reason = err.reason; | ||
if (reason) { | ||
return reason === 'saved' ? Promise.resolve(err.data) : Promise.reject(err); | ||
} | ||
var config = err.config; | ||
if (config) { | ||
stack.remove(config); | ||
var custom_1 = config[conf.prop]; | ||
var isResend = conf.isResend, resendDelay_1 = conf.resendDelay, resendTimes = conf.resendTimes, curResendTimes_1 = 0; | ||
if (custom_1) { | ||
isResend = notUndef(custom_1.isResend, isResend); | ||
resendDelay_1 = notUndef(custom_1.resendDelay, resendDelay_1); | ||
resendTimes = notUndef(custom_1.resendTimes, resendTimes); | ||
curResendTimes_1 = notUndef(custom_1.curResendTimes, 0); | ||
if (isError(data)) { | ||
if (isDef(data.reason)) { | ||
return 'reasonError'; | ||
} | ||
if (isResend) { | ||
if (curResendTimes_1 < resendTimes) { | ||
return new Promise(function (resolve) { | ||
setTimeout(function () { | ||
if (!custom_1) { | ||
config.custom = {}; | ||
} | ||
config.custom.curResendTimes = ++curResendTimes_1; | ||
if (isStr(config.data)) { | ||
config.data = JSON.parse(config.data); | ||
} | ||
return resolve(axios.request(config)); | ||
}, resendDelay_1); | ||
}); | ||
} | ||
else { | ||
error = { reason: 'resendEnd', message: "Can't get a response." }; | ||
return Promise.reject(error); | ||
} | ||
} | ||
else { | ||
return Promise.reject(err); | ||
} | ||
return 'error'; | ||
} | ||
}); | ||
} | ||
else { | ||
return 'undefined'; | ||
} | ||
} | ||
function transformSyncData(data) { | ||
switch (dataType(data)) { | ||
case 'undefined': return; | ||
case 'error': return new ReasonError(data); | ||
default: return data; | ||
} | ||
} | ||
var normalize = (function (data) { | ||
var result = transformSyncData(data); | ||
if (result instanceof Promise) { | ||
return result.then(function (data) { return transformSyncData(data); }, function (data) { return transformSyncData(data); }); | ||
} | ||
else { | ||
return result; | ||
} | ||
}); | ||
function requestInterceptors (sugar, stack) { | ||
var axios = sugar.axios; | ||
var storage = sugar.storage; | ||
var conf = sugar.config; | ||
var lifecycle = sugar.lifecycle; | ||
var error; | ||
axios.interceptors.request.use(function (config) { | ||
config = normalizeProp(config, conf.prop); | ||
if (stack.contains(config)) { | ||
error = { reason: 'existed' }; | ||
return Promise.reject(error); | ||
function initInterceptors(axiosSugar) { | ||
axiosSugar.interceptors.request.use(function (config) { | ||
middleData.configs.push(config); | ||
config.index = repeat.call(axiosSugar, config); | ||
return config; | ||
}, function (err) { | ||
return Promise.reject(err); | ||
}); | ||
axiosSugar.interceptors.response.use(function (config) { | ||
if (storage.set(config)) { | ||
var stored = axiosSugar.events['stored']; | ||
if (isFn(stored)) { | ||
stored.call(axiosSugar, config); | ||
} | ||
} | ||
var custom = config[conf.prop]; | ||
var isSave = conf.isSave; | ||
if (custom) { | ||
isSave = notUndef(custom.isSave, isSave); | ||
if (!isInInterval(config.sendingTime, config.completeTime, config.sugar.repeat.interval)) { | ||
dataDestory(config.index); | ||
} | ||
if (isSave) { | ||
var storageRes = storage.get(genSymbol(config)); | ||
if (storageRes) { | ||
error = { reason: 'saved', data: storageRes }; | ||
return Promise.reject(error); | ||
} | ||
return axiosSugar.httpStatusProcessor.dispatch(axiosSugar, config.response.status.toString(), config); | ||
}, function (err) { | ||
var result = err; | ||
if ((err.reason && | ||
!isInInterval(err.sendingTime, err.completeTime, err.sugar.repeat.interval))) { | ||
dataDestory(err.index); | ||
} | ||
var cycleRes = lifecycle.beforeRequest(config); | ||
if (!cycleRes.state) { | ||
error = { reason: 'beforeRequestBreak', message: cycleRes.message }; | ||
return Promise.reject(error); | ||
if (err.reason && err.reason.response) { | ||
result = axiosSugar.httpStatusProcessor.dispatch(axiosSugar, err.reason.response.status.toString(), err); | ||
} | ||
stack.push(config); | ||
return Promise.resolve(config); | ||
}, function (err) { | ||
Promise.reject(err); | ||
result = normalize(result); | ||
if (result instanceof Promise && err.count >= 1) { | ||
dataDestory(err.index); | ||
} | ||
return result instanceof Promise ? result : Promise.reject(result || err); | ||
}); | ||
} | ||
var AxiosSugarLifeCycle = (function () { | ||
function AxiosSugarLifeCycle() { | ||
function retryFn (err) { | ||
var _this = this; | ||
if (isNum(err.count)) { | ||
err.count += 1; | ||
} | ||
AxiosSugarLifeCycle.prototype.beforeRequest = function (conf) { | ||
return { | ||
state: true, | ||
message: '' | ||
else { | ||
err.count = 1; | ||
} | ||
if (isNum(err.sugar.retry.count) && | ||
err.count <= err.sugar.retry.count) { | ||
var retried = _this.events['retried']; | ||
if (retried) { | ||
retried.call(_this, err); | ||
} | ||
return new Promise(function (resolve, reject) { | ||
setTimeout(function () { | ||
reject(_this.request(err)); | ||
}, err.sugar.retry.delay); | ||
}); | ||
} | ||
else { | ||
var retryFailed = _this.events['retryFailed']; | ||
if (isFn(retryFailed)) { | ||
retryFailed.call(_this, err); | ||
} | ||
return new Error('[axios-sugar]: retryFiled.'); | ||
} | ||
} | ||
var HttpStatusProcessorPrototype = (function () { | ||
function HttpStatusProcessorPrototype() { | ||
this.statusTable = { | ||
400: this.onBadRequest, | ||
401: this.onUnauthorized, | ||
403: this.onForbidden, | ||
404: this.onNotFound, | ||
405: this.onMethodNotAllow, | ||
406: this.onNotAcceptable, | ||
407: this.onProxyAuthenticationRequired, | ||
408: this.onTimeout, | ||
409: this.onConflict, | ||
500: this.onInternalServerError, | ||
501: this.onNotImplemented, | ||
502: this.onBadGateway | ||
}; | ||
this.reservedCodes = Object.keys(this.statusTable); | ||
} | ||
HttpStatusProcessorPrototype.prototype.setStatusHandler = function (status, fn) { | ||
if (this.reservedCodes.indexOf(status) < 0) { | ||
this.statusTable[status] = fn; | ||
return true; | ||
} | ||
else if (isDev()) { | ||
error("can't set the handler of http status code " + status + "."); | ||
} | ||
return false; | ||
}; | ||
AxiosSugarLifeCycle.prototype.beforeResponse = function (res) { | ||
return { | ||
state: true, | ||
message: '' | ||
}; | ||
HttpStatusProcessorPrototype.prototype.dispatch = function (axiosSugar, status, payload) { | ||
var firstCode = status.toString().substr(0, 1); | ||
var result = payload.response; | ||
var isRetried = false; | ||
var retriedRequest = undefined; | ||
var retry = (payload.reason && | ||
payload.sugar.retry.enable) ? function () { | ||
if (!isRetried) { | ||
isRetried = true; | ||
retriedRequest = retryFn.call(axiosSugar, payload); | ||
return true; | ||
} | ||
else if (isDev()) { | ||
warn('retry has been already called'); | ||
} | ||
return false; | ||
} : undefined; | ||
function handlerCall(fn, result) { | ||
return fn.call(axiosSugar, status, payload, result, retry); | ||
} | ||
if (isFn(this["on" + firstCode + "XXBefore"])) { | ||
result = handlerCall(this["on" + firstCode + "XXBefore"], result); | ||
} | ||
else if (isFn(this.onStatusBefore)) { | ||
result = handlerCall(this.onStatusBefore, result); | ||
} | ||
if (isFn(this.statusTable[status])) { | ||
result = handlerCall(this.statusTable[status], result); | ||
} | ||
if (isFn(this["on" + firstCode + "XXAfter"])) { | ||
result = handlerCall(this["on" + firstCode + "XXAfter"], result); | ||
} | ||
else if (isFn(this.onStatusAfter)) { | ||
result = handlerCall(this.onStatusAfter, result); | ||
} | ||
return retriedRequest || result; | ||
}; | ||
return AxiosSugarLifeCycle; | ||
return HttpStatusProcessorPrototype; | ||
}()); | ||
var HttpStatusProcessor = (function (_super) { | ||
__extends(HttpStatusProcessor, _super); | ||
function HttpStatusProcessor() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
return HttpStatusProcessor; | ||
}(HttpStatusProcessorPrototype)); | ||
var errorhandlers = [ | ||
'BadRequest', | ||
'Unauthorized', | ||
'Forbidden', | ||
'NotFound', | ||
'MethodNotAllow', | ||
'NotAcceptable', | ||
'ProxyAuthenticationRequired', | ||
'Conflict', | ||
'InternalServerError', | ||
'NotImplemented', | ||
'BadGateway' | ||
]; | ||
function autoRetry(axiosSugar, err, retry) { | ||
if (retry && err.sugar.retry.auto) { | ||
if (!retry()) { | ||
warn('retry has been already retried before'); | ||
} | ||
} | ||
} | ||
errorhandlers.forEach(function (h) { | ||
HttpStatusProcessor.prototype['on' + h] = function (status, err, result, retry) { | ||
if (isDev()) { | ||
error(err.reason.message); | ||
} | ||
autoRetry(this, err, retry); | ||
return err.reason; | ||
}; | ||
}); | ||
HttpStatusProcessor.prototype.on = function (event, fn) { | ||
this['on' + capitalize(event)] = fn; | ||
}; | ||
HttpStatusProcessor.prototype['onTimeout'] = function (status, err, result, retry) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var onlineCheck, onlineTimeout, offline; | ||
var _this = this; | ||
return __generator(this, function (_a) { | ||
onlineCheck = err.sugar.onlineCheck; | ||
if (onlineCheck.enable) { | ||
if (isOnline()) { | ||
if (isDev()) { | ||
error("online but timeout"); | ||
} | ||
onlineTimeout = this.events['onlineTimeout']; | ||
if (isFn(onlineTimeout)) { | ||
this.events['onlineTimeout'].call(this, err, retry); | ||
} | ||
autoRetry(this, err, retry); | ||
} | ||
else { | ||
if (isDev()) { | ||
error("offline"); | ||
} | ||
offline = this.events['offline']; | ||
if (isFn(offline)) { | ||
this.events['offline'].call(this, err); | ||
} | ||
if (onlineCheck.reconnect.enable) { | ||
window.addEventListener('online', function () { | ||
var online = _this.events['online']; | ||
if (isFn(online)) { | ||
_this.events['online'].call(_this, err, retry); | ||
autoRetry(_this, err, retry); | ||
} | ||
}); | ||
} | ||
} | ||
} | ||
else { | ||
if (isDev()) { | ||
error(err.reason.message); | ||
} | ||
autoRetry(this, err, retry); | ||
} | ||
return [2, err.reason]; | ||
}); | ||
}); | ||
}; | ||
function mergeConfig(target, source) { | ||
var result = deepMerge$1(target, source); | ||
if (source.save && source.save.storage) { | ||
result.save.storage = source.save.storage; | ||
} | ||
else { | ||
result.save.storage = target.save.storage; | ||
} | ||
return result; | ||
} | ||
var httpStatusProcessor = new HttpStatusProcessor(); | ||
var AxiosSugar = (function () { | ||
function AxiosSugar(axios, options) { | ||
function AxiosSugar(axiosConfig, config) { | ||
this.httpStatusProcessor = httpStatusProcessor; | ||
this.axios = axios.create(axiosConfig); | ||
this.config = config || Object.assign({}, defaults); | ||
this.events = {}; | ||
this.interceptors = { | ||
request: new AxiosSugarInterceptorManager(), | ||
response: new AxiosSugarInterceptorManager() | ||
}; | ||
initInterceptors(this); | ||
} | ||
AxiosSugar.prototype.request = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var axiosConfig; | ||
var config; | ||
var _this = this; | ||
if (options === void 0) { options = {}; } | ||
this.stack = new AxiosSugarRequestStack(); | ||
this.config = new AxiosSugarConfig(); | ||
this.storage = new AxiosSugarInnerStorage(); | ||
this.lifecycle = new AxiosSugarLifeCycle(); | ||
this.axios = axios; | ||
['config', 'storage', 'lifecycle'].forEach(function (option) { | ||
if (options[option]) { | ||
_this[option] = options[option]; | ||
} | ||
if (isStr(args[0])) { | ||
axiosConfig = args[1] || {}; | ||
axiosConfig.url = args[0]; | ||
config = args[2]; | ||
} | ||
else { | ||
axiosConfig = args[0] || {}; | ||
config = args[1]; | ||
} | ||
config = config ? mergeConfig(defaults, config) : _this.config; | ||
var chain = [dispatchRequest.bind(this), undefined]; | ||
var middleResponseError = axiosConfig; | ||
var data = middleResponseError.isAxiosSugarError ? { | ||
axios: middleResponseError.axios, | ||
sugar: middleResponseError.sugar, | ||
count: isNum(middleResponseError.count) ? middleResponseError.count : middleResponseError.count | ||
} : { | ||
axios: axiosConfig, | ||
sugar: config, | ||
cancelDisabled: false | ||
}; | ||
var promise = Promise.resolve(data); | ||
_this.interceptors.request.each(function (interceptor) { | ||
chain.unshift(interceptor.fulfilled, interceptor.rejected); | ||
}); | ||
this.init(); | ||
} | ||
AxiosSugar.prototype.init = function () { | ||
requestInterceptors(this, this.stack); | ||
responseInterceptors(this, this.stack); | ||
_this.interceptors.response.each(function (interceptor) { | ||
chain.push(interceptor.fulfilled, interceptor.rejected); | ||
}); | ||
while (chain.length) { | ||
promise = promise.then(chain.shift(), chain.shift()); | ||
} | ||
return promise; | ||
}; | ||
AxiosSugar.prototype.on = function (event, fn) { | ||
this.events[event] = fn; | ||
}; | ||
AxiosSugar.prototype.off = function (event, fn) { | ||
if (this.events[event] === fn) { | ||
this.events[event] = undefined; | ||
return true; | ||
} | ||
return false; | ||
}; | ||
return AxiosSugar; | ||
}()); | ||
var usedAxios = new AxiosStack(); | ||
function factory(axios, options) { | ||
if (options === void 0) { options = {}; } | ||
if (usedAxios.contains(axios)) { | ||
console.error('[axios-sugar]: an axios static or instance only can call factory once.'); | ||
['delete', 'get', 'head', 'options'].forEach(function (method) { | ||
AxiosSugar.prototype[method] = function (url, axiosConfig, config) { | ||
return this.request(merge$1(axiosConfig || {}, { | ||
method: method, | ||
url: url | ||
}), config); | ||
}; | ||
}); | ||
['post', 'put', 'patch'].forEach(function (method) { | ||
AxiosSugar.prototype[method] = function (url, data, axiosConfig, config) { | ||
return this.request(merge$1(axiosConfig || {}, { | ||
method: method, | ||
url: url, | ||
data: data | ||
}), config); | ||
}; | ||
}); | ||
var AxiosSugarStatic = (function (_super) { | ||
__extends(AxiosSugarStatic, _super); | ||
function AxiosSugarStatic() { | ||
var _this_1 = _super.call(this) || this; | ||
_this_1.repeatTag = repeatTag; | ||
_this_1.defaults = defaults; | ||
_this_1.axiosDefaults = axios.defaults; | ||
_this_1.axios = axios; | ||
return _this_1; | ||
} | ||
else { | ||
usedAxios.push(axios); | ||
return new AxiosSugar(axios, options); | ||
} | ||
} | ||
AxiosSugarStatic.prototype.create = function (axiosConfig, config) { | ||
if (config) { | ||
config = mergeConfig(defaults, config); | ||
} | ||
return new AxiosSugar(axiosConfig, config); | ||
}; | ||
AxiosSugarStatic.prototype.isCancel = function (err) { | ||
if (err.reason) { | ||
return axios.isCancel(err.reason); | ||
} | ||
else { | ||
return false; | ||
} | ||
}; | ||
AxiosSugarStatic.prototype.getUri = function (config) { | ||
return axios.getUri(config); | ||
}; | ||
AxiosSugarStatic.prototype.spread = function (fn) { | ||
return axios.spread(fn); | ||
}; | ||
AxiosSugarStatic.prototype.all = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return axios.all(args); | ||
}; | ||
AxiosSugarStatic.prototype.cancelAll = function () { | ||
var cancelConfigs = []; | ||
middleData.configs.map(function (c) { | ||
if (c !== null) { | ||
cancelConfigs.push({ | ||
cancel: middleData.cancels[c.index], | ||
config: c | ||
}); | ||
} | ||
}); | ||
if (isFn(this.cancelFilter)) { | ||
cancelConfigs = this.cancelFilter(cancelConfigs); | ||
} | ||
cancelConfigs.forEach(function (c) { | ||
c.cancel(); | ||
}); | ||
}; | ||
AxiosSugarStatic.prototype.cancelFilter = function (cancelConfigs) { | ||
return cancelConfigs.filter(function (c) { return !c.config.cancelDisabled; }); | ||
}; | ||
AxiosSugarStatic.prototype.cancelAutoRetry = function (err) { | ||
err.sugar.retry.auto = false; | ||
}; | ||
return AxiosSugarStatic; | ||
}(AxiosSugar)); | ||
var SugarStatic = new AxiosSugarStatic(); | ||
exports.AxiosSugarConfig = AxiosSugarConfig; | ||
exports.AxiosSugarInnerReleaseStorage = AxiosSugarInnerReleaseStorage; | ||
exports.AxiosSugarInnerStorage = AxiosSugarInnerStorage; | ||
exports.AxiosSugarLifeCycle = AxiosSugarLifeCycle; | ||
exports.AxiosSugarLocalStorage = AxiosSugarLocalStorage; | ||
exports.default = factory; | ||
var storage$1 = { | ||
inner: AxiosSugarInnerStorage, | ||
local: AxiosSugarLocalStorage | ||
}; | ||
exports.AxiosSugar = AxiosSugar; | ||
exports.HttpStatusProcessor = HttpStatusProcessor; | ||
exports.default = SugarStatic; | ||
exports.storage = storage$1; |
@@ -1,463 +0,998 @@ | ||
var AxiosSugar = (function (exports) { | ||
'use strict'; | ||
var AxiosSugar = (function (exports, axios) { | ||
'use strict'; | ||
function isDef(value) { | ||
return typeof value !== 'undefined'; | ||
} | ||
function isStr(value) { | ||
return typeof value === 'string'; | ||
} | ||
function getDurationMS(a, b) { | ||
return a - b; | ||
} | ||
axios = axios && Object.prototype.hasOwnProperty.call(axios, 'default') ? axios['default'] : axios; | ||
var AxiosSugarConfig = (function () { | ||
function AxiosSugarConfig(options) { | ||
this.isResend = false; | ||
this.resendDelay = 1000; | ||
this.resendTimes = 3; | ||
this.isSave = false; | ||
this.prop = 'custom'; | ||
options = options || {}; | ||
for (var _i = 0, _a = Object.keys(options); _i < _a.length; _i++) { | ||
var key = _a[_i]; | ||
if (isDef(this[key])) { | ||
this[key] = options[key]; | ||
} | ||
else { | ||
console.error("[axios sugar]: the option " + key + " is not valid."); | ||
} | ||
} | ||
} | ||
return AxiosSugarConfig; | ||
}()); | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. All rights reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use | ||
this file except in compliance with the License. You may obtain a copy of the | ||
License at http://www.apache.org/licenses/LICENSE-2.0 | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. All rights reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use | ||
this file except in compliance with the License. You may obtain a copy of the | ||
License at http://www.apache.org/licenses/LICENSE-2.0 | ||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED | ||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, | ||
MERCHANTABLITY OR NON-INFRINGEMENT. | ||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED | ||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, | ||
MERCHANTABLITY OR NON-INFRINGEMENT. | ||
See the Apache Version 2.0 License for specific language governing permissions | ||
and limitations under the License. | ||
***************************************************************************** */ | ||
/* global Reflect, Promise */ | ||
See the Apache Version 2.0 License for specific language governing permissions | ||
and limitations under the License. | ||
***************************************************************************** */ | ||
/* global Reflect, Promise */ | ||
var extendStatics = function(d, b) { | ||
extendStatics = Object.setPrototypeOf || | ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; | ||
return extendStatics(d, b); | ||
}; | ||
var extendStatics = function(d, b) { | ||
extendStatics = Object.setPrototypeOf || | ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; | ||
return extendStatics(d, b); | ||
}; | ||
function __extends(d, b) { | ||
extendStatics(d, b); | ||
function __() { this.constructor = d; } | ||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | ||
} | ||
function __extends(d, b) { | ||
extendStatics(d, b); | ||
function __() { this.constructor = d; } | ||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | ||
} | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
var ECMA_SIZES = { | ||
STRING: 2, | ||
BOOLEAN: 4, | ||
NUMBER: 8 | ||
}; | ||
function __generator(thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
} | ||
var isBrowser = typeof window !== 'undefined'; | ||
var Buffer; | ||
if (!isBrowser) { | ||
Buffer = require('buffer').Buffer; | ||
} | ||
function sizeOfObject(seen, object) { | ||
if (object == null) { | ||
return 0; | ||
} | ||
var bytes = 0; | ||
for (var key in object) { | ||
if (typeof object[key] === 'object' && object[key] !== null) { | ||
if (seen.has(object[key])) { | ||
continue; | ||
} | ||
seen.add(object[key]); | ||
} | ||
bytes += getCalculator(seen)(key); | ||
try { | ||
bytes += getCalculator(seen)(object[key]); | ||
} | ||
catch (ex) { | ||
if (ex instanceof RangeError) { | ||
bytes = 0; | ||
} | ||
} | ||
} | ||
return bytes; | ||
} | ||
function getCalculator(seen) { | ||
return function (object) { | ||
if (!isBrowser && Buffer.isBuffer(object)) { | ||
return object.length; | ||
} | ||
var objectType = typeof (object); | ||
switch (objectType) { | ||
case 'string': | ||
return object.length * ECMA_SIZES.STRING; | ||
case 'boolean': | ||
return ECMA_SIZES.BOOLEAN; | ||
case 'number': | ||
return ECMA_SIZES.NUMBER; | ||
case 'object': | ||
if (Array.isArray(object)) { | ||
return object.map(getCalculator(seen)).reduce(function (acc, curr) { | ||
return acc + curr; | ||
}, 0); | ||
} | ||
else { | ||
return sizeOfObject(seen, object); | ||
} | ||
default: | ||
return 0; | ||
} | ||
}; | ||
} | ||
function sizeof(object) { | ||
return getCalculator(new WeakSet())(object); | ||
} | ||
function isArray(val) { | ||
return toString.call(val) === '[object Array]'; | ||
} | ||
function forEach(obj, fn) { | ||
if (obj === null || typeof obj === 'undefined') { | ||
return; | ||
} | ||
if (typeof obj !== 'object') { | ||
obj = [obj]; | ||
} | ||
if (isArray(obj)) { | ||
for (var i = 0, l = obj.length; i < l; i++) { | ||
fn.call(null, obj[i], i, obj); | ||
} | ||
} | ||
else { | ||
for (var key in obj) { | ||
if (Object.prototype.hasOwnProperty.call(obj, key)) { | ||
fn.call(null, obj[key], key, obj); | ||
} | ||
} | ||
} | ||
} | ||
function merge() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var result = {}; | ||
function assignValue(val, key) { | ||
if (typeof result[key] === 'object' && typeof val === 'object') { | ||
result[key] = merge(result[key], val); | ||
} | ||
else { | ||
result[key] = val; | ||
} | ||
} | ||
for (var i = 0, l = arguments.length; i < l; i++) { | ||
forEach(args[i], assignValue); | ||
} | ||
return result; | ||
} | ||
function deepMerge() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var result = {}; | ||
function assignValue(val, key) { | ||
if (typeof result[key] === 'object' && typeof val === 'object') { | ||
result[key] = deepMerge(result[key], val); | ||
} | ||
else if (typeof val === 'object') { | ||
result[key] = deepMerge({}, val); | ||
} | ||
else { | ||
result[key] = val; | ||
} | ||
} | ||
for (var i = 0, l = arguments.length; i < l; i++) { | ||
forEach(args[i], assignValue); | ||
} | ||
return result; | ||
} | ||
var AxiosSugarInnerStorage = (function () { | ||
function AxiosSugarInnerStorage() { | ||
this.data = {}; | ||
} | ||
AxiosSugarInnerStorage.prototype.set = function (symbol, res) { | ||
this.data[symbol] = res; | ||
}; | ||
AxiosSugarInnerStorage.prototype.get = function (symbol) { | ||
return this.data[symbol] || null; | ||
}; | ||
AxiosSugarInnerStorage.prototype.contains = function (symbol) { | ||
return typeof this.data[symbol] !== 'undefined'; | ||
}; | ||
return AxiosSugarInnerStorage; | ||
}()); | ||
var AxiosSugarInnerReleaseStorage = (function (_super) { | ||
__extends(AxiosSugarInnerReleaseStorage, _super); | ||
function AxiosSugarInnerReleaseStorage(duration, limit) { | ||
var _this = _super.call(this) || this; | ||
_this.duration = 5 * 60 * 1000; | ||
_this.limit = 15 * 1024 * 1024; | ||
if (isDef(duration)) | ||
_this.duration = duration; | ||
if (isDef(limit)) | ||
_this.limit = limit; | ||
return _this; | ||
} | ||
AxiosSugarInnerReleaseStorage.prototype.set = function (symbol, res) { | ||
var data = this.data; | ||
for (var _i = 0, _a = Object.entries(data); _i < _a.length; _i++) { | ||
var _b = _a[_i], key = _b[0], item = _b[1]; | ||
if (getDurationMS(new Date().getTime(), item.time) >= this.duration) { | ||
delete data[key]; | ||
} | ||
} | ||
if (sizeof(res) + sizeof(data) > this.limit) { | ||
data = this.data = {}; | ||
} | ||
data[symbol] = { | ||
data: res, | ||
time: new Date().getTime() | ||
}; | ||
}; | ||
AxiosSugarInnerReleaseStorage.prototype.get = function (symbol) { | ||
var target = this.data[symbol]; | ||
return target ? target.data : null; | ||
}; | ||
return AxiosSugarInnerReleaseStorage; | ||
}(AxiosSugarInnerStorage)); | ||
var AxiosSugarLocalStorage = (function () { | ||
function AxiosSugarLocalStorage() { | ||
} | ||
AxiosSugarLocalStorage.prototype.set = function (symbol, res) { | ||
try { | ||
localStorage.setItem(symbol, JSON.stringify(res)); | ||
} | ||
catch (err) { | ||
console.error("[axios-sugar]: " + err.message); | ||
} | ||
}; | ||
AxiosSugarLocalStorage.prototype.get = function (symbol) { | ||
var data = localStorage.getItem(symbol); | ||
return data === null ? null : JSON.parse(data); | ||
}; | ||
AxiosSugarLocalStorage.prototype.contains = function (symbol) { | ||
return this.get(symbol) !== null; | ||
}; | ||
return AxiosSugarLocalStorage; | ||
}()); | ||
function capitalize(str) { | ||
return str.substring(0, 1).toUpperCase() + str.substring(1); | ||
} | ||
function isDef(value) { | ||
return typeof value !== 'undefined'; | ||
} | ||
function isStr(value) { | ||
return typeof value === 'string'; | ||
} | ||
function isError(value) { | ||
return value instanceof Error; | ||
} | ||
function getDurationMS(a, b) { | ||
return a - b; | ||
} | ||
function customMessage(msg) { | ||
return "[axios-sugar]: " + msg + "."; | ||
} | ||
function warn(msg) { | ||
console.warn(customMessage(msg)); | ||
} | ||
function error(msg) { | ||
console.error(customMessage(msg)); | ||
} | ||
function throwError(msg) { | ||
throw new Error(customMessage(msg)); | ||
} | ||
function isDev() { | ||
return process.env.NODE_ENV === 'development'; | ||
} | ||
function isFn(val) { | ||
return typeof val === 'function'; | ||
} | ||
function isNum(val) { | ||
return typeof val === 'number'; | ||
} | ||
function deepMerge$1() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return deepMerge.apply(null, args); | ||
} | ||
function merge$1() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return merge.apply(null, args); | ||
} | ||
function isOnline(options) { | ||
return navigator.onLine; | ||
} | ||
var Stack = (function () { | ||
function Stack() { | ||
this.stack = []; | ||
} | ||
Stack.prototype.push = function (el) { | ||
return this.stack.push(el); | ||
}; | ||
Stack.prototype.pop = function () { | ||
return this.stack.pop(); | ||
}; | ||
Stack.prototype.contains = function (el) { | ||
return this.stack.indexOf(el) >= 0; | ||
}; | ||
Stack.prototype.remove = function (el) { | ||
return this.stack.splice(this.indexOf(el), 1)[0]; | ||
}; | ||
Stack.prototype.indexOf = function (el) { | ||
return this.stack.indexOf(el); | ||
}; | ||
return Stack; | ||
}()); | ||
var AxiosSugarRequestStack = (function (_super) { | ||
__extends(AxiosSugarRequestStack, _super); | ||
function AxiosSugarRequestStack() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
AxiosSugarRequestStack.prototype.forEach = function (cb) { | ||
this.stack.forEach(function (conf, confIdx, thisArg) { | ||
cb.call(conf, conf, confIdx, thisArg); | ||
}); | ||
}; | ||
return AxiosSugarRequestStack; | ||
}(Stack)); | ||
var AxiosStack = (function (_super) { | ||
__extends(AxiosStack, _super); | ||
function AxiosStack() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
return AxiosStack; | ||
}(Stack)); | ||
var ECMA_SIZES = { | ||
STRING: 2, | ||
BOOLEAN: 4, | ||
NUMBER: 8 | ||
}; | ||
function sendDataWay(method) { | ||
var isInData = ['post', 'put', 'patch'].indexOf(method) >= 0, isInParams = method === 'get'; | ||
return isInData ? 'data' : (isInParams ? 'params' : 'both'); | ||
} | ||
function normalizeProp(config, prop) { | ||
if (prop === void 0) { prop = 'custom'; } | ||
if (sendDataWay(config.method) === 'data' && config.data) { | ||
var propVal = config.data[prop]; | ||
if (propVal) { | ||
config[prop] = propVal; | ||
delete config.data[prop]; | ||
} | ||
} | ||
return config; | ||
} | ||
function genSymbol(config) { | ||
var url = config.url; | ||
var method = config.method; | ||
var data; | ||
function getParamsSymbolData(params) { | ||
var data = ''; | ||
if (/\?/.test(url)) { | ||
var part = url.split('?'); | ||
url = part[0]; | ||
data += part[1]; | ||
} | ||
if (params) { | ||
for (var _i = 0, _a = Object.entries(params); _i < _a.length; _i++) { | ||
var _b = _a[_i], key = _b[0], val = _b[1]; | ||
if (data !== '') | ||
data += '&'; | ||
data += key + "=" + val; | ||
} | ||
} | ||
return data; | ||
} | ||
function getDataSymbolData(data) { | ||
return isDef(data) ? JSON.stringify(data) : ''; | ||
} | ||
switch (sendDataWay(method)) { | ||
case 'params': | ||
data = getParamsSymbolData(config.params); | ||
break; | ||
case 'data': | ||
data = getDataSymbolData(config.data); | ||
break; | ||
case 'both': | ||
data = getParamsSymbolData(config.params) || getDataSymbolData(config.params); | ||
} | ||
return "method=" + method + "&url=" + url + "&data=" + data; | ||
} | ||
function notUndef(targetVal, defaultVal) { | ||
return typeof targetVal === 'undefined' ? defaultVal : targetVal; | ||
} | ||
var isBrowser = typeof window !== 'undefined'; | ||
var Buffer; | ||
if (!isBrowser) { | ||
Buffer = require('buffer').Buffer; | ||
} | ||
function sizeOfObject(seen, object) { | ||
if (object == null) { | ||
return 0; | ||
} | ||
var bytes = 0; | ||
for (var key in object) { | ||
if (typeof object[key] === 'object' && object[key] !== null) { | ||
if (seen.has(object[key])) { | ||
continue; | ||
} | ||
seen.add(object[key]); | ||
} | ||
bytes += getCalculator(seen)(key); | ||
try { | ||
bytes += getCalculator(seen)(object[key]); | ||
} | ||
catch (ex) { | ||
if (ex instanceof RangeError) { | ||
bytes = 0; | ||
} | ||
} | ||
} | ||
return bytes; | ||
} | ||
function getCalculator(seen) { | ||
return function (object) { | ||
if (!isBrowser && Buffer.isBuffer(object)) { | ||
return object.length; | ||
} | ||
var objectType = typeof (object); | ||
switch (objectType) { | ||
case 'string': | ||
return object.length * ECMA_SIZES.STRING; | ||
case 'boolean': | ||
return ECMA_SIZES.BOOLEAN; | ||
case 'number': | ||
return ECMA_SIZES.NUMBER; | ||
case 'object': | ||
if (Array.isArray(object)) { | ||
return object.map(getCalculator(seen)).reduce(function (acc, curr) { | ||
return acc + curr; | ||
}, 0); | ||
} | ||
else { | ||
return sizeOfObject(seen, object); | ||
} | ||
default: | ||
return 0; | ||
} | ||
}; | ||
} | ||
function sizeof(object) { | ||
return getCalculator(new WeakSet())(object); | ||
} | ||
function responseInterceptors (sugar, stack) { | ||
var axios = sugar.axios; | ||
var storage = sugar.storage; | ||
var conf = sugar.config; | ||
var lifecycle = sugar.lifecycle; | ||
var error; | ||
axios.interceptors.response.use(function (res) { | ||
var config = res.config; | ||
var resData = res.data; | ||
var cycleRes = lifecycle.beforeResponse(res); | ||
if (!cycleRes.state) { | ||
error = { reason: 'beforeResponseBreak', message: cycleRes.message }; | ||
return Promise.reject(error); | ||
} | ||
if (config) { | ||
stack.remove(config); | ||
} | ||
var custom = config.custom; | ||
var isSave; | ||
if (custom) { | ||
isSave = notUndef(custom.isSave, conf.isSave); | ||
} | ||
if (isSave) { | ||
var symbol = genSymbol(config); | ||
storage.set(symbol, resData); | ||
} | ||
return Promise.resolve(resData); | ||
}, function (err) { | ||
var reason = err.reason; | ||
if (reason) { | ||
return reason === 'saved' ? Promise.resolve(err.data) : Promise.reject(err); | ||
} | ||
var config = err.config; | ||
if (config) { | ||
stack.remove(config); | ||
var custom_1 = config[conf.prop]; | ||
var isResend = conf.isResend, resendDelay_1 = conf.resendDelay, resendTimes = conf.resendTimes, curResendTimes_1 = 0; | ||
if (custom_1) { | ||
isResend = notUndef(custom_1.isResend, isResend); | ||
resendDelay_1 = notUndef(custom_1.resendDelay, resendDelay_1); | ||
resendTimes = notUndef(custom_1.resendTimes, resendTimes); | ||
curResendTimes_1 = notUndef(custom_1.curResendTimes, 0); | ||
} | ||
if (isResend) { | ||
if (curResendTimes_1 < resendTimes) { | ||
return new Promise(function (resolve) { | ||
setTimeout(function () { | ||
if (!custom_1) { | ||
config.custom = {}; | ||
} | ||
config.custom.curResendTimes = ++curResendTimes_1; | ||
if (isStr(config.data)) { | ||
config.data = JSON.parse(config.data); | ||
} | ||
return resolve(axios.request(config)); | ||
}, resendDelay_1); | ||
}); | ||
} | ||
else { | ||
error = { reason: 'resendEnd', message: "Can't get a response." }; | ||
return Promise.reject(error); | ||
} | ||
} | ||
else { | ||
return Promise.reject(err); | ||
} | ||
} | ||
}); | ||
} | ||
var innerStorageDefaults = { | ||
release: false, | ||
duration: 5 * 60 * 1000, | ||
limit: 15 * 1024 * 1024 | ||
}; | ||
var AxiosSugarInnerStorage = (function () { | ||
function AxiosSugarInnerStorage(config) { | ||
this.data = {}; | ||
this.config = config ? merge$1(innerStorageDefaults, config) : innerStorageDefaults; | ||
} | ||
AxiosSugarInnerStorage.prototype.release = function (tag, data) { | ||
if (this.config.release && isDef(this.data[tag])) { | ||
if (this.config.duration) { | ||
var time = this.data[tag].time; | ||
if (getDurationMS(new Date().getTime(), time) >= this.config.duration) { | ||
this.data[tag] = undefined; | ||
} | ||
} | ||
else if (isDef(data) && | ||
sizeof(this.data) + sizeof(data) > this.config.limit) { | ||
if (isFn(this.full)) { | ||
this.full(tag, data); | ||
} | ||
} | ||
} | ||
}; | ||
AxiosSugarInnerStorage.prototype.full = function (tag, data) { | ||
throwError('The capacity of the storage is full'); | ||
}; | ||
AxiosSugarInnerStorage.prototype.set = function (tag, data) { | ||
try { | ||
this.release(tag, data); | ||
this.data[tag] = data; | ||
return true; | ||
} | ||
catch (err) { | ||
if (isDev()) { | ||
error(err.message); | ||
} | ||
return false; | ||
} | ||
}; | ||
AxiosSugarInnerStorage.prototype.get = function (tag) { | ||
this.release(tag); | ||
return this.data[tag] || null; | ||
}; | ||
return AxiosSugarInnerStorage; | ||
}()); | ||
var AxiosSugarLocalStorage = (function () { | ||
function AxiosSugarLocalStorage() { | ||
this.data = {}; | ||
} | ||
AxiosSugarLocalStorage.prototype.set = function (tag, data) { | ||
try { | ||
localStorage.setItem(tag, JSON.stringify(data)); | ||
return true; | ||
} | ||
catch (err) { | ||
if (isDev()) { | ||
error(err.message); | ||
} | ||
return false; | ||
} | ||
}; | ||
AxiosSugarLocalStorage.prototype.get = function (tag) { | ||
var data = localStorage.getItem(tag); | ||
return data === null ? null : JSON.parse(data); | ||
}; | ||
return AxiosSugarLocalStorage; | ||
}()); | ||
function requestInterceptors (sugar, stack) { | ||
var axios = sugar.axios; | ||
var storage = sugar.storage; | ||
var conf = sugar.config; | ||
var lifecycle = sugar.lifecycle; | ||
var error; | ||
axios.interceptors.request.use(function (config) { | ||
config = normalizeProp(config, conf.prop); | ||
if (stack.contains(config)) { | ||
error = { reason: 'existed' }; | ||
return Promise.reject(error); | ||
} | ||
var custom = config[conf.prop]; | ||
var isSave = conf.isSave; | ||
if (custom) { | ||
isSave = notUndef(custom.isSave, isSave); | ||
} | ||
if (isSave) { | ||
var storageRes = storage.get(genSymbol(config)); | ||
if (storageRes) { | ||
error = { reason: 'saved', data: storageRes }; | ||
return Promise.reject(error); | ||
} | ||
} | ||
var cycleRes = lifecycle.beforeRequest(config); | ||
if (!cycleRes.state) { | ||
error = { reason: 'beforeRequestBreak', message: cycleRes.message }; | ||
return Promise.reject(error); | ||
} | ||
stack.push(config); | ||
return Promise.resolve(config); | ||
}, function (err) { | ||
Promise.reject(err); | ||
}); | ||
} | ||
var defaults = { | ||
repeat: { | ||
interval: 2000 | ||
}, | ||
onlineCheck: { | ||
enable: false, | ||
reconnect: { | ||
enable: true | ||
} | ||
}, | ||
save: { | ||
enable: false, | ||
storage: new AxiosSugarInnerStorage() | ||
}, | ||
retry: { | ||
enable: false, | ||
auto: true, | ||
count: 3, | ||
delay: 2000 | ||
} | ||
}; | ||
var AxiosSugarLifeCycle = (function () { | ||
function AxiosSugarLifeCycle() { | ||
} | ||
AxiosSugarLifeCycle.prototype.beforeRequest = function (conf) { | ||
return { | ||
state: true, | ||
message: '' | ||
}; | ||
}; | ||
AxiosSugarLifeCycle.prototype.beforeResponse = function (res) { | ||
return { | ||
state: true, | ||
message: '' | ||
}; | ||
}; | ||
return AxiosSugarLifeCycle; | ||
}()); | ||
var AxiosSugarInterceptorManager = (function () { | ||
function AxiosSugarInterceptorManager() { | ||
this.handlers = []; | ||
} | ||
AxiosSugarInterceptorManager.prototype.use = function (fulfilled, rejected) { | ||
this.handlers.push({ | ||
fulfilled: fulfilled, | ||
rejected: rejected | ||
}); | ||
return this.handlers.length - 1; | ||
}; | ||
AxiosSugarInterceptorManager.prototype.eject = function (i) { | ||
if (this.handlers[i]) { | ||
this.handlers[i] = null; | ||
} | ||
}; | ||
AxiosSugarInterceptorManager.prototype.each = function (fn) { | ||
this.handlers.forEach(function (handler) { | ||
if (handler !== null) { | ||
fn(handler); | ||
} | ||
}); | ||
}; | ||
return AxiosSugarInterceptorManager; | ||
}()); | ||
var AxiosSugar = (function () { | ||
function AxiosSugar(axios, options) { | ||
var _this = this; | ||
if (options === void 0) { options = {}; } | ||
this.stack = new AxiosSugarRequestStack(); | ||
this.config = new AxiosSugarConfig(); | ||
this.storage = new AxiosSugarInnerStorage(); | ||
this.lifecycle = new AxiosSugarLifeCycle(); | ||
this.axios = axios; | ||
['config', 'storage', 'lifecycle'].forEach(function (option) { | ||
if (options[option]) { | ||
_this[option] = options[option]; | ||
} | ||
}); | ||
this.init(); | ||
} | ||
AxiosSugar.prototype.init = function () { | ||
requestInterceptors(this, this.stack); | ||
responseInterceptors(this, this.stack); | ||
}; | ||
return AxiosSugar; | ||
}()); | ||
var usedAxios = new AxiosStack(); | ||
function factory(axios, options) { | ||
if (options === void 0) { options = {}; } | ||
if (usedAxios.contains(axios)) { | ||
console.error('[axios-sugar]: an axios static or instance only can call factory once.'); | ||
} | ||
else { | ||
usedAxios.push(axios); | ||
return new AxiosSugar(axios, options); | ||
} | ||
} | ||
var middleData = { | ||
tags: [], | ||
cancels: [], | ||
configs: [] | ||
}; | ||
function dataDestory(index) { | ||
middleData.configs[index] = null; | ||
if (middleData.tags[index] !== null) { | ||
middleData.tags[index] = null; | ||
middleData.cancels[index] = null; | ||
} | ||
} | ||
exports.AxiosSugarConfig = AxiosSugarConfig; | ||
exports.AxiosSugarInnerReleaseStorage = AxiosSugarInnerReleaseStorage; | ||
exports.AxiosSugarInnerStorage = AxiosSugarInnerStorage; | ||
exports.AxiosSugarLifeCycle = AxiosSugarLifeCycle; | ||
exports.AxiosSugarLocalStorage = AxiosSugarLocalStorage; | ||
exports.default = factory; | ||
var storage = { | ||
get: function (config) { | ||
var save = config.sugar.save; | ||
if (save.enable) { | ||
var storage = save.storage; | ||
var tag = middleData.tags[config.index]; | ||
if (tag !== null) { | ||
return storage.get(tag); | ||
} | ||
} | ||
return null; | ||
}, | ||
set: function (config) { | ||
var save = config.sugar.save; | ||
if (save.enable) { | ||
var storage = save.storage; | ||
var tag = middleData.tags[config.index]; | ||
if (tag !== null) { | ||
storage.set(tag, { | ||
response: config.response, | ||
time: new Date().getTime() | ||
}); | ||
return true; | ||
} | ||
} | ||
return false; | ||
} | ||
}; | ||
return exports; | ||
var MiddleResponseError = (function (_super) { | ||
__extends(MiddleResponseError, _super); | ||
function MiddleResponseError(reason, config) { | ||
var _newTarget = this.constructor; | ||
var _this = _super.call(this, reason.message) || this; | ||
_this.name = _newTarget.name; | ||
if (typeof Error.captureStackTrace === 'function') { | ||
Error.captureStackTrace(_this, (_newTarget)); | ||
} | ||
if (typeof Object.setPrototypeOf === 'function') { | ||
Object.setPrototypeOf(_this, _newTarget.prototype); | ||
} | ||
else { | ||
_this.__proto__ = _newTarget.prototype; | ||
} | ||
_this.reason = reason; | ||
_this.axios = config.axios; | ||
_this.index = config.index; | ||
_this.sugar = config.sugar; | ||
_this.count = config.count; | ||
_this.sendingTime = config.sendingTime; | ||
_this.completeTime = config.completeTime; | ||
_this.isAxiosSugarError = true; | ||
return _this; | ||
} | ||
return MiddleResponseError; | ||
}(Error)); | ||
function dispatchRequest (config) { | ||
var cache = config.sugar.save.enable ? storage.get(config) : null; | ||
config.sendingTime = new Date().getTime(); | ||
if (cache !== null) { | ||
return Promise.resolve({ | ||
response: cache.response, | ||
sugar: config.sugar, | ||
index: config.index, | ||
sendingTime: config.sendingTime, | ||
cacheTime: cache.time, | ||
completeTime: new Date().getTime() | ||
}); | ||
} | ||
else { | ||
return this.axios.request(config.axios).then(function (response) { | ||
config.completeTime = new Date().getTime(); | ||
return { | ||
response: response, | ||
sugar: config.sugar, | ||
index: config.index, | ||
sendingTime: config.sendingTime, | ||
completeTime: config.completeTime | ||
}; | ||
}, function (reason) { | ||
config.completeTime = new Date().getTime(); | ||
var error = new MiddleResponseError(reason, config); | ||
return Promise.reject(error); | ||
}); | ||
} | ||
} | ||
}({})); | ||
function sendDataWay(method) { | ||
var isInData = ['post', 'put', 'patch'].indexOf(method) >= 0; | ||
return isInData ? 'data' : 'params'; | ||
} | ||
function querystring(url) { | ||
var result = {}; | ||
var index = url.indexOf('?'); | ||
if (index >= 0) { | ||
var arr = url.trim().substring(url.indexOf()).split('&'); | ||
arr.forEach(function (item) { | ||
var arr = item.trim().split('='); | ||
if (arr.length === 1) { | ||
result[arr[0]] = ''; | ||
} | ||
else { | ||
result[arr[0]] = result[arr[1]]; | ||
} | ||
}); | ||
} | ||
return result; | ||
} | ||
function getDataString(data) { | ||
return data ? JSON.stringify(data) : ''; | ||
} | ||
function genSymbol(config) { | ||
var url = config.url; | ||
var method = config.method; | ||
var data; | ||
switch (sendDataWay(method)) { | ||
case 'params': { | ||
data = config.params || {}; | ||
if (method === 'get') { | ||
data = deepMerge$1(querystring(url), data); | ||
} | ||
data = getDataString(data); | ||
break; | ||
} | ||
case 'data': data = getDataString(config.data); | ||
} | ||
return "method=" + method + "&url=" + url + "&data=" + data; | ||
} | ||
function isInInterval(sendingTime, completeTime, interval) { | ||
return getDurationMS(completeTime, sendingTime) < interval; | ||
} | ||
function repeatTag(axiosConfig, config) { | ||
return genSymbol(axiosConfig); | ||
} | ||
function repeat (config) { | ||
var _this = this; | ||
var tag = SugarStatic.repeatTag(config.axios, config.sugar); | ||
var i = middleData.tags.indexOf(tag); | ||
if (i >= 0 && | ||
middleData.configs[i].sendingTime && | ||
!isInInterval(middleData.configs[i].sendingTime, new Date().getTime(), config.sugar.repeat.interval)) { | ||
dataDestory(i); | ||
i = -1; | ||
} | ||
var callRepeated = function () { | ||
var repeated = _this.events['repeated']; | ||
if (isFn(repeated)) { | ||
repeated.call(_this, config); | ||
} | ||
}; | ||
if (i >= 0) { | ||
if (middleData.configs[i] && middleData.configs[i].completeTime) { | ||
callRepeated(); | ||
throwError('The current request is repeated.'); | ||
} | ||
else { | ||
middleData.cancels[i]('The previous request is repeated.'); | ||
middleData.tags[i] = null; | ||
middleData.cancels[i] = null; | ||
callRepeated(); | ||
} | ||
} | ||
var source = axios.CancelToken.source(); | ||
config.axios.cancelToken = source.token; | ||
middleData.cancels.push(source.cancel); | ||
return middleData.tags.push(tag) - 1; | ||
} | ||
var ReasonError = (function (_super) { | ||
__extends(ReasonError, _super); | ||
function ReasonError(error) { | ||
var _newTarget = this.constructor; | ||
var _this = _super.call(this, error.message) || this; | ||
_this.name = _newTarget.name; | ||
if (typeof Error.captureStackTrace === 'function') { | ||
Error.captureStackTrace(_this, (_newTarget)); | ||
} | ||
if (typeof Object.setPrototypeOf === 'function') { | ||
Object.setPrototypeOf(_this, _newTarget.prototype); | ||
} | ||
else { | ||
_this.__proto__ = _newTarget.prototype; | ||
} | ||
_this.reason = error; | ||
return _this; | ||
} | ||
return ReasonError; | ||
}(Error)); | ||
function dataType(data) { | ||
if (isDef(data)) { | ||
if (data instanceof Promise) { | ||
return 'promise'; | ||
} | ||
if (isError(data)) { | ||
if (isDef(data.reason)) { | ||
return 'reasonError'; | ||
} | ||
return 'error'; | ||
} | ||
} | ||
else { | ||
return 'undefined'; | ||
} | ||
} | ||
function transformSyncData(data) { | ||
switch (dataType(data)) { | ||
case 'undefined': return; | ||
case 'error': return new ReasonError(data); | ||
default: return data; | ||
} | ||
} | ||
var normalize = (function (data) { | ||
var result = transformSyncData(data); | ||
if (result instanceof Promise) { | ||
return result.then(function (data) { return transformSyncData(data); }, function (data) { return transformSyncData(data); }); | ||
} | ||
else { | ||
return result; | ||
} | ||
}); | ||
function initInterceptors(axiosSugar) { | ||
axiosSugar.interceptors.request.use(function (config) { | ||
middleData.configs.push(config); | ||
config.index = repeat.call(axiosSugar, config); | ||
return config; | ||
}, function (err) { | ||
return Promise.reject(err); | ||
}); | ||
axiosSugar.interceptors.response.use(function (config) { | ||
if (storage.set(config)) { | ||
var stored = axiosSugar.events['stored']; | ||
if (isFn(stored)) { | ||
stored.call(axiosSugar, config); | ||
} | ||
} | ||
if (!isInInterval(config.sendingTime, config.completeTime, config.sugar.repeat.interval)) { | ||
dataDestory(config.index); | ||
} | ||
return axiosSugar.httpStatusProcessor.dispatch(axiosSugar, config.response.status.toString(), config); | ||
}, function (err) { | ||
var result = err; | ||
if ((err.reason && | ||
!isInInterval(err.sendingTime, err.completeTime, err.sugar.repeat.interval))) { | ||
dataDestory(err.index); | ||
} | ||
if (err.reason && err.reason.response) { | ||
result = axiosSugar.httpStatusProcessor.dispatch(axiosSugar, err.reason.response.status.toString(), err); | ||
} | ||
result = normalize(result); | ||
if (result instanceof Promise && err.count >= 1) { | ||
dataDestory(err.index); | ||
} | ||
return result instanceof Promise ? result : Promise.reject(result || err); | ||
}); | ||
} | ||
function retryFn (err) { | ||
var _this = this; | ||
if (isNum(err.count)) { | ||
err.count += 1; | ||
} | ||
else { | ||
err.count = 1; | ||
} | ||
if (isNum(err.sugar.retry.count) && | ||
err.count <= err.sugar.retry.count) { | ||
var retried = _this.events['retried']; | ||
if (retried) { | ||
retried.call(_this, err); | ||
} | ||
return new Promise(function (resolve, reject) { | ||
setTimeout(function () { | ||
reject(_this.request(err)); | ||
}, err.sugar.retry.delay); | ||
}); | ||
} | ||
else { | ||
var retryFailed = _this.events['retryFailed']; | ||
if (isFn(retryFailed)) { | ||
retryFailed.call(_this, err); | ||
} | ||
return new Error('[axios-sugar]: retryFiled.'); | ||
} | ||
} | ||
var HttpStatusProcessorPrototype = (function () { | ||
function HttpStatusProcessorPrototype() { | ||
this.statusTable = { | ||
400: this.onBadRequest, | ||
401: this.onUnauthorized, | ||
403: this.onForbidden, | ||
404: this.onNotFound, | ||
405: this.onMethodNotAllow, | ||
406: this.onNotAcceptable, | ||
407: this.onProxyAuthenticationRequired, | ||
408: this.onTimeout, | ||
409: this.onConflict, | ||
500: this.onInternalServerError, | ||
501: this.onNotImplemented, | ||
502: this.onBadGateway | ||
}; | ||
this.reservedCodes = Object.keys(this.statusTable); | ||
} | ||
HttpStatusProcessorPrototype.prototype.setStatusHandler = function (status, fn) { | ||
if (this.reservedCodes.indexOf(status) < 0) { | ||
this.statusTable[status] = fn; | ||
return true; | ||
} | ||
else if (isDev()) { | ||
error("can't set the handler of http status code " + status + "."); | ||
} | ||
return false; | ||
}; | ||
HttpStatusProcessorPrototype.prototype.dispatch = function (axiosSugar, status, payload) { | ||
var firstCode = status.toString().substr(0, 1); | ||
var result = payload.response; | ||
var isRetried = false; | ||
var retriedRequest = undefined; | ||
var retry = (payload.reason && | ||
payload.sugar.retry.enable) ? function () { | ||
if (!isRetried) { | ||
isRetried = true; | ||
retriedRequest = retryFn.call(axiosSugar, payload); | ||
return true; | ||
} | ||
else if (isDev()) { | ||
warn('retry has been already called'); | ||
} | ||
return false; | ||
} : undefined; | ||
function handlerCall(fn, result) { | ||
return fn.call(axiosSugar, status, payload, result, retry); | ||
} | ||
if (isFn(this["on" + firstCode + "XXBefore"])) { | ||
result = handlerCall(this["on" + firstCode + "XXBefore"], result); | ||
} | ||
else if (isFn(this.onStatusBefore)) { | ||
result = handlerCall(this.onStatusBefore, result); | ||
} | ||
if (isFn(this.statusTable[status])) { | ||
result = handlerCall(this.statusTable[status], result); | ||
} | ||
if (isFn(this["on" + firstCode + "XXAfter"])) { | ||
result = handlerCall(this["on" + firstCode + "XXAfter"], result); | ||
} | ||
else if (isFn(this.onStatusAfter)) { | ||
result = handlerCall(this.onStatusAfter, result); | ||
} | ||
return retriedRequest || result; | ||
}; | ||
return HttpStatusProcessorPrototype; | ||
}()); | ||
var HttpStatusProcessor = (function (_super) { | ||
__extends(HttpStatusProcessor, _super); | ||
function HttpStatusProcessor() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
return HttpStatusProcessor; | ||
}(HttpStatusProcessorPrototype)); | ||
var errorhandlers = [ | ||
'BadRequest', | ||
'Unauthorized', | ||
'Forbidden', | ||
'NotFound', | ||
'MethodNotAllow', | ||
'NotAcceptable', | ||
'ProxyAuthenticationRequired', | ||
'Conflict', | ||
'InternalServerError', | ||
'NotImplemented', | ||
'BadGateway' | ||
]; | ||
function autoRetry(axiosSugar, err, retry) { | ||
if (retry && err.sugar.retry.auto) { | ||
if (!retry()) { | ||
warn('retry has been already retried before'); | ||
} | ||
} | ||
} | ||
errorhandlers.forEach(function (h) { | ||
HttpStatusProcessor.prototype['on' + h] = function (status, err, result, retry) { | ||
if (isDev()) { | ||
error(err.reason.message); | ||
} | ||
autoRetry(this, err, retry); | ||
return err.reason; | ||
}; | ||
}); | ||
HttpStatusProcessor.prototype.on = function (event, fn) { | ||
this['on' + capitalize(event)] = fn; | ||
}; | ||
HttpStatusProcessor.prototype['onTimeout'] = function (status, err, result, retry) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var onlineCheck, onlineTimeout, offline; | ||
var _this = this; | ||
return __generator(this, function (_a) { | ||
onlineCheck = err.sugar.onlineCheck; | ||
if (onlineCheck.enable) { | ||
if (isOnline()) { | ||
if (isDev()) { | ||
error("online but timeout"); | ||
} | ||
onlineTimeout = this.events['onlineTimeout']; | ||
if (isFn(onlineTimeout)) { | ||
this.events['onlineTimeout'].call(this, err, retry); | ||
} | ||
autoRetry(this, err, retry); | ||
} | ||
else { | ||
if (isDev()) { | ||
error("offline"); | ||
} | ||
offline = this.events['offline']; | ||
if (isFn(offline)) { | ||
this.events['offline'].call(this, err); | ||
} | ||
if (onlineCheck.reconnect.enable) { | ||
window.addEventListener('online', function () { | ||
var online = _this.events['online']; | ||
if (isFn(online)) { | ||
_this.events['online'].call(_this, err, retry); | ||
autoRetry(_this, err, retry); | ||
} | ||
}); | ||
} | ||
} | ||
} | ||
else { | ||
if (isDev()) { | ||
error(err.reason.message); | ||
} | ||
autoRetry(this, err, retry); | ||
} | ||
return [2, err.reason]; | ||
}); | ||
}); | ||
}; | ||
function mergeConfig(target, source) { | ||
var result = deepMerge$1(target, source); | ||
if (source.save && source.save.storage) { | ||
result.save.storage = source.save.storage; | ||
} | ||
else { | ||
result.save.storage = target.save.storage; | ||
} | ||
return result; | ||
} | ||
var httpStatusProcessor = new HttpStatusProcessor(); | ||
var AxiosSugar = (function () { | ||
function AxiosSugar(axiosConfig, config) { | ||
this.httpStatusProcessor = httpStatusProcessor; | ||
this.axios = axios.create(axiosConfig); | ||
this.config = config || Object.assign({}, defaults); | ||
this.events = {}; | ||
this.interceptors = { | ||
request: new AxiosSugarInterceptorManager(), | ||
response: new AxiosSugarInterceptorManager() | ||
}; | ||
initInterceptors(this); | ||
} | ||
AxiosSugar.prototype.request = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var axiosConfig; | ||
var config; | ||
var _this = this; | ||
if (isStr(args[0])) { | ||
axiosConfig = args[1] || {}; | ||
axiosConfig.url = args[0]; | ||
config = args[2]; | ||
} | ||
else { | ||
axiosConfig = args[0] || {}; | ||
config = args[1]; | ||
} | ||
config = config ? mergeConfig(defaults, config) : _this.config; | ||
var chain = [dispatchRequest.bind(this), undefined]; | ||
var middleResponseError = axiosConfig; | ||
var data = middleResponseError.isAxiosSugarError ? { | ||
axios: middleResponseError.axios, | ||
sugar: middleResponseError.sugar, | ||
count: isNum(middleResponseError.count) ? middleResponseError.count : middleResponseError.count | ||
} : { | ||
axios: axiosConfig, | ||
sugar: config, | ||
cancelDisabled: false | ||
}; | ||
var promise = Promise.resolve(data); | ||
_this.interceptors.request.each(function (interceptor) { | ||
chain.unshift(interceptor.fulfilled, interceptor.rejected); | ||
}); | ||
_this.interceptors.response.each(function (interceptor) { | ||
chain.push(interceptor.fulfilled, interceptor.rejected); | ||
}); | ||
while (chain.length) { | ||
promise = promise.then(chain.shift(), chain.shift()); | ||
} | ||
return promise; | ||
}; | ||
AxiosSugar.prototype.on = function (event, fn) { | ||
this.events[event] = fn; | ||
}; | ||
AxiosSugar.prototype.off = function (event, fn) { | ||
if (this.events[event] === fn) { | ||
this.events[event] = undefined; | ||
return true; | ||
} | ||
return false; | ||
}; | ||
return AxiosSugar; | ||
}()); | ||
['delete', 'get', 'head', 'options'].forEach(function (method) { | ||
AxiosSugar.prototype[method] = function (url, axiosConfig, config) { | ||
return this.request(merge$1(axiosConfig || {}, { | ||
method: method, | ||
url: url | ||
}), config); | ||
}; | ||
}); | ||
['post', 'put', 'patch'].forEach(function (method) { | ||
AxiosSugar.prototype[method] = function (url, data, axiosConfig, config) { | ||
return this.request(merge$1(axiosConfig || {}, { | ||
method: method, | ||
url: url, | ||
data: data | ||
}), config); | ||
}; | ||
}); | ||
var AxiosSugarStatic = (function (_super) { | ||
__extends(AxiosSugarStatic, _super); | ||
function AxiosSugarStatic() { | ||
var _this_1 = _super.call(this) || this; | ||
_this_1.repeatTag = repeatTag; | ||
_this_1.defaults = defaults; | ||
_this_1.axiosDefaults = axios.defaults; | ||
_this_1.axios = axios; | ||
return _this_1; | ||
} | ||
AxiosSugarStatic.prototype.create = function (axiosConfig, config) { | ||
if (config) { | ||
config = mergeConfig(defaults, config); | ||
} | ||
return new AxiosSugar(axiosConfig, config); | ||
}; | ||
AxiosSugarStatic.prototype.isCancel = function (err) { | ||
if (err.reason) { | ||
return axios.isCancel(err.reason); | ||
} | ||
else { | ||
return false; | ||
} | ||
}; | ||
AxiosSugarStatic.prototype.getUri = function (config) { | ||
return axios.getUri(config); | ||
}; | ||
AxiosSugarStatic.prototype.spread = function (fn) { | ||
return axios.spread(fn); | ||
}; | ||
AxiosSugarStatic.prototype.all = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return axios.all(args); | ||
}; | ||
AxiosSugarStatic.prototype.cancelAll = function () { | ||
var cancelConfigs = []; | ||
middleData.configs.map(function (c) { | ||
if (c !== null) { | ||
cancelConfigs.push({ | ||
cancel: middleData.cancels[c.index], | ||
config: c | ||
}); | ||
} | ||
}); | ||
if (isFn(this.cancelFilter)) { | ||
cancelConfigs = this.cancelFilter(cancelConfigs); | ||
} | ||
cancelConfigs.forEach(function (c) { | ||
c.cancel(); | ||
}); | ||
}; | ||
AxiosSugarStatic.prototype.cancelFilter = function (cancelConfigs) { | ||
return cancelConfigs.filter(function (c) { return !c.config.cancelDisabled; }); | ||
}; | ||
AxiosSugarStatic.prototype.cancelAutoRetry = function (err) { | ||
err.sugar.retry.auto = false; | ||
}; | ||
return AxiosSugarStatic; | ||
}(AxiosSugar)); | ||
var SugarStatic = new AxiosSugarStatic(); | ||
var storage$1 = { | ||
inner: AxiosSugarInnerStorage, | ||
local: AxiosSugarLocalStorage | ||
}; | ||
exports.AxiosSugar = AxiosSugar; | ||
exports.HttpStatusProcessor = HttpStatusProcessor; | ||
exports.default = SugarStatic; | ||
exports.storage = storage$1; | ||
return exports; | ||
}({}, axios)); |
{ | ||
"name": "axios-sugar", | ||
"version": "1.2.0", | ||
"description": "An axios wrapper, which supports resending, store and so on", | ||
"version": "2.0.0-0", | ||
"description": "A wrapper for axios", | ||
"main": "dist/axios-sugar.cjs.js", | ||
@@ -13,2 +13,3 @@ "scripts": { | ||
"test": "npx mocha --reporter spec --require ts-node/register test/**/*.test.ts", | ||
"testone": "npx mocha --reporter spec --require ts-node/register", | ||
"publish": "npm publish --registry https://registry.npmjs.org", | ||
@@ -25,3 +26,3 @@ "cover": "npx nyc npm test", | ||
"src/index.ts", | ||
"src/AxiosSugarStorage.ts" | ||
"src/core/AxiosSugarStorage.ts" | ||
], | ||
@@ -51,22 +52,32 @@ "extension": [ | ||
"devDependencies": { | ||
"@types/chai": "^4.2.9", | ||
"@types/mocha": "^7.0.1", | ||
"@typescript-eslint/eslint-plugin": "^2.19.2", | ||
"@typescript-eslint/parser": "^2.19.2", | ||
"axios": "^0.19.2", | ||
"axios-mock-adapter": "^1.17.0", | ||
"babel-eslint": "^10.1.0", | ||
"@types/chai": "^4.2.12", | ||
"@types/mocha": "^7.0.2", | ||
"@typescript-eslint/eslint-plugin": "^2.34.0", | ||
"@typescript-eslint/parser": "^2.34.0", | ||
"axios-mock-adapter": "^1.18.2", | ||
"chai": "^4.2.0", | ||
"coveralls": "^3.0.9", | ||
"coveralls": "^3.1.0", | ||
"cz-conventional-changelog": "^3.2.0", | ||
"eslint": "^6.8.0", | ||
"istanbul": "^0.4.5", | ||
"mocha": "^7.1.0", | ||
"mocha": "^7.2.0", | ||
"node-localstorage": "^2.1.5", | ||
"rollup": "^1.31.0", | ||
"rollup": "^1.32.1", | ||
"rollup-plugin-typescript2": "^0.25.3", | ||
"rollup-plugin-uglify": "^6.0.4", | ||
"ts-node": "^8.6.2", | ||
"typescript": "^3.7.5" | ||
"ts-node": "^8.10.2", | ||
"typescript": "^3.9.7" | ||
}, | ||
"dependencies": {} | ||
"dependencies": { | ||
"axios": "^0.19.2", | ||
"object-sizeof": "^1.6.1" | ||
}, | ||
"config": { | ||
"commitizen": { | ||
"path": "./node_modules/cz-conventional-changelog" | ||
} | ||
}, | ||
"keywords": [ | ||
"axios", "wrapper" | ||
] | ||
} |
260
README.md
@@ -7,232 +7,51 @@ ![Travis (.org)](https://img.shields.io/travis/maoyonglong/axios-sugar) | ||
# Locales | ||
[简体中文](./locales/README-zh.md) | ||
# AxiosSugar | ||
An axios wrapper, which supports resending, storage, cancel repeat request automatically; and so on. | ||
An wrapper for axios.js | ||
# Usage | ||
```js | ||
import axios from 'axios' | ||
// This is a factory to new AxiosSugar Class | ||
import factory from 'axios-sugar' | ||
# Carefully | ||
The new version has significant changes and is not compatible with the old version. | ||
Compared with the old version, it is used in a very similar way to Axios. | ||
factory(axios); | ||
// or | ||
const ins = axios.create(); | ||
factory(ins); | ||
# Features | ||
* Axios-Like Methods | ||
* Cancel Repeated Requests | ||
* Retry | ||
* Response Storage | ||
* Broken Network Retransmission | ||
* Handlers for Http-Status-Code Responses | ||
* Cancel All Requests Matched By Filter | ||
// In version 1.1.3-0, it is suggested to use factory instead of AxiosSugar class | ||
// If you really need this class, you can use as follow: | ||
import axios from 'axios' | ||
import { AxiosSugar } from 'axios-sugar' | ||
const axiosSugar = new AxiosSugar(axios); | ||
// but carefully, an axios instance only can be call `new AxiosSugar()` once | ||
// now you can use axios as before | ||
axios.get(); | ||
// or | ||
ins.get(); | ||
// ... | ||
``` | ||
# Config | ||
# Usage | ||
```js | ||
import axios from 'axios' | ||
import factory, { AxiosSugarConfig } from 'axios-sugar' | ||
import AxiosSugar from 'axios-sugar'; | ||
// AxiosSugarConfigOptions | ||
let options = { | ||
isResend: true, | ||
isSave: true | ||
} | ||
factory(axios, { | ||
config: new AxiosSugarConfig(options) | ||
}); | ||
``` | ||
### AxiosSugarConfigOptions | ||
```js | ||
{ | ||
isResend?: boolean; // default: false | ||
resendDelay?: number; // default: 1000 (ms) | ||
resendTimes?: number; // default: 3 | ||
isSave?: boolean; // default: false | ||
prop?: string; // default: custom to override the options above in a special request | ||
} | ||
``` | ||
prop is a property injected in the config of axios: | ||
```js | ||
import axios from 'axios' | ||
import factory, { AxiosSugarConfig } from 'axios-sugar' | ||
// AxiosSugarConfigOptions | ||
let options = { | ||
isResend: true, | ||
isSave: true // default to use innerStorage | ||
} | ||
factory(axios, { | ||
config: new AxiosSugarConfig(options) | ||
}); | ||
axios.get('/path', { | ||
// prop | ||
custom: { | ||
isSave: false // Now, this request will not be saved. | ||
// suppose the request returns paramA | ||
AxiosSugar.get('/somePath', { | ||
params: { | ||
paramA: 1 | ||
} | ||
}).then(res => { | ||
console.log(res.data); // 1 | ||
}) | ||
axios.get('/path') // This request will be saved | ||
``` | ||
# Storage | ||
This library supports two way to save the response data`(res.data in axios.then)`. | ||
### InnerStorage | ||
This storage will be save the data in a object variable. | ||
Look, it's really like Axios!The *request*, *get*, *post*, *delete*, *put*, *patch*, *head*, *options* is also. | ||
The difference is that these methods also receive an [AxiosSugarConfig](https://maoyonglong.github.io/guide/configuration) type parameter. | ||
e.g. | ||
```js | ||
import axios from 'axios' | ||
import factory, { AxiosSugarInnerStorage } from 'axios-sugar' | ||
let options = { | ||
isSave: true // default to use innerStorage | ||
} | ||
factory(axios, { | ||
config: new AxiosSugarConfig(options), | ||
storage: new AxiosSugarInnerStorage() // storage | ||
}); | ||
``` | ||
### InnerReleaseStorage | ||
Unlike InnerStorage, it can automatically free up memory. | ||
```js | ||
import axios from 'axios' | ||
import factory, { AxiosSugarInnerReleaseStorage } from 'axios-sugar' | ||
let options = { | ||
isSave: true // default to use innerStorage | ||
} | ||
factory(axios, { | ||
config: new AxiosSugarConfig(options), | ||
storage: new AxiosSugarInnerReleaseStorage() // storage | ||
}); | ||
// the constructor of AxiosSugarInnerReleaseStorage is: | ||
/** | ||
* duration: storage time (ms) default is 5 * 60 * 1000 (i.e. 5 minutes) | ||
* limit: memory limit (Bytes) default is 15 * 1024 * 1024 (i.e. 15MB) | ||
* constructor (duration: number, limit: number); | ||
* / | ||
``` | ||
### LocalStorage | ||
This storage will be save the data in localStorage. | ||
```js | ||
import axios from 'axios' | ||
import factory, { AxiosSugarLocalStorage } from 'axios-sugar' | ||
let options = { | ||
isSave: true // default to use innerStorage | ||
} | ||
factory(axios, { | ||
config: new AxiosSugarConfig(options), | ||
storage: new AxiosSugarLocalStorage() // storage | ||
}); | ||
``` | ||
### Custom Storage | ||
You can implements the interface AxiosSugarStorage to customize your storage. | ||
// The interface is: | ||
```ts | ||
interface AxiosSugarStorage { | ||
set (symbol: string, res: any): void; | ||
get (symbol: string): any; | ||
contains (symbol: string): boolean; | ||
} | ||
``` | ||
// custom: | ||
```js | ||
import axios from 'axios' | ||
import factory from 'axios-sugar' | ||
let options = { | ||
isSave: true // default to use innerStorage | ||
} | ||
// override set, get and contains methods | ||
class CustomStorage { | ||
// symbol is a string to identify a request, res is `res.data in axios.then` | ||
set (symbol: string, res: any); | ||
get (symbol: string); | ||
contains (symbol: string); | ||
} | ||
factory(axios, { | ||
config: new AxiosSugarConfig(options), | ||
storage: new CustomStorage() // storage | ||
}); | ||
``` | ||
# Lifecycle | ||
The lifecycle is some callback. | ||
```js | ||
import axios from 'axios' | ||
import factory{ AxiosSugarLifeCycle } from 'axios-sugar' | ||
let cycle = new AxiosSugarLifeCycle(); | ||
// now, you can override some callback | ||
cycle.beforeRequest = (conf) => { | ||
return false // This will break the request | ||
} | ||
factory(axios, { | ||
lifecycle: cycle | ||
AxiosSugar.get('/somePath', { | ||
params: { | ||
paramA: 1 | ||
} | ||
}, { | ||
retry: { | ||
enable: true | ||
} | ||
}) | ||
``` | ||
### callback | ||
The callback of lifecycle is: | ||
```ts | ||
beforeRequest(conf: AxiosRequestConfig): AxiosSugarLifeCycleResult; | ||
// carefully, this res is the `res` not `res.data` | ||
beforeResponse(res: AxiosResponse): AxiosSugarLifeCycleResult; | ||
``` | ||
All callback should return an AxiosSugarLifeCycleResult, it is a object: | ||
```ts | ||
{ | ||
state: false, // will break execution and throw an AxiosSugarError if state is false | ||
message: '', // error message | ||
} | ||
``` | ||
### AxiosSugarError | ||
The AxiosSugarError is: | ||
```ts | ||
{ | ||
reason: string; // error reason | ||
message?: any; | ||
data?: any; | ||
} | ||
``` | ||
Next, you should get more details in [references](https://maoyonglong.github.io/axios-sugar-docs/guide) | ||
### AxiosSugarError Handler | ||
You can catch the errors in `axios.catch` | ||
```js | ||
axios.get() | ||
.catch(err => { | ||
/** | ||
* AxiosSugarError | ||
* reason may be: | ||
* beforeRequestBreak | ||
* beforeResponseBreak | ||
* existed | ||
* ... | ||
*/ | ||
if (err.readon) { | ||
console.log(err) | ||
} | ||
// an axios error | ||
else { | ||
// ... | ||
} | ||
}) | ||
``` | ||
# Test | ||
@@ -245,8 +64,1 @@ **Node test**: | ||
open the corresponding `index.html` File in `/test` which built by mocha. | ||
# TODO | ||
* Broken network retransmission | ||
* Broken network lifecycle | ||
# Change Log | ||
v1.1.3-0 export default a factory instead of exporting an AxiosSugar class |
@@ -5,7 +5,7 @@ { | ||
"declarationDir": "types", | ||
"removeComments": true | ||
"removeComments": true, | ||
"esModuleInterop": true | ||
}, | ||
"include": [ | ||
"src", | ||
"node_modules/axios/lib/utils.js" | ||
"src" | ||
], | ||
@@ -12,0 +12,0 @@ "exclude": [ |
@@ -1,20 +0,61 @@ | ||
import { AxiosInstance, AxiosStatic } from '../vendor/axios'; | ||
import AxiosSugarConfig from '../AxiosSugarConfig'; | ||
import { AxiosSugarStorage } from '../AxiosSugarStorage'; | ||
import AxiosSugarLifeCycle from '../AxiosSugarLifeCycle'; | ||
interface AxiosSugarOptions { | ||
config?: AxiosSugarConfig; | ||
storage?: AxiosSugarStorage; | ||
lifecycle?: AxiosSugarLifeCycle; | ||
import { AxiosSugarConfig } from '../defaults'; | ||
import { AxiosSugarInterceptorManager } from './AxiosSugarInterceptorManager'; | ||
import { AxiosRequestConfig, AxiosInstance } from 'axios/index'; | ||
import { MiddleRequestConfig } from './dispatchRequest'; | ||
import { repeatTag } from './repeat'; | ||
import HttpStatusProcessor from './HttpStatusProcessor'; | ||
import { MiddleResponseError } from './dispatchRequest'; | ||
export interface Interceptors { | ||
request: AxiosSugarInterceptorManager; | ||
response: AxiosSugarInterceptorManager; | ||
} | ||
export default class AxiosSugar { | ||
private stack; | ||
axios: AxiosInstance | AxiosStatic; | ||
declare type Event = 'retried' | 'retryFailed' | 'stored' | 'repeated' | 'offline' | 'onlineTimeout' | 'online'; | ||
declare type Events = { | ||
[key in Event]: Function; | ||
} | {}; | ||
interface spreadCallback { | ||
(...args: unknown[]): any; | ||
} | ||
interface CancelConfig { | ||
cancel: Function; | ||
config: MiddleRequestConfig; | ||
} | ||
export declare class AxiosSugar { | ||
axios: AxiosInstance; | ||
interceptors: Interceptors; | ||
config: AxiosSugarConfig; | ||
storage: AxiosSugarStorage; | ||
lifecycle: AxiosSugarLifeCycle; | ||
constructor(axios: AxiosInstance | AxiosStatic, options?: AxiosSugarOptions); | ||
private init; | ||
events: Events; | ||
httpStatusProcessor: HttpStatusProcessor; | ||
[key: string]: any; | ||
get: (url: string, axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig) => Promise<any>; | ||
post: (url: string, axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig) => Promise<any>; | ||
head: (url: string, axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig) => Promise<any>; | ||
options: (url: string, axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig) => Promise<any>; | ||
delete: (url: string, axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig) => Promise<any>; | ||
put: (url: string, axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig) => Promise<any>; | ||
patch: (url: string, axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig) => Promise<any>; | ||
request(axiosConfig: AxiosRequestConfig | MiddleResponseError, config?: AxiosSugarConfig): Promise<any>; | ||
request(url: string, axiosConfig?: AxiosRequestConfig | MiddleResponseError, config?: AxiosSugarConfig): Promise<any>; | ||
on(event: Event, fn: Function): void; | ||
off(event: Event, fn: Function): Boolean; | ||
constructor(axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig); | ||
} | ||
export declare function factory(axios: AxiosInstance | AxiosStatic, options?: AxiosSugarOptions): undefined | AxiosSugar; | ||
declare class AxiosSugarStatic extends AxiosSugar { | ||
defaults: AxiosSugarConfig; | ||
axiosDefaults: AxiosRequestConfig; | ||
axios: AxiosInstance; | ||
static AxiosSugarStatic: (axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig) => AxiosSugar; | ||
[key: string]: any; | ||
create(axiosConfig?: AxiosRequestConfig, config?: AxiosSugarConfig): AxiosSugar; | ||
repeatTag: typeof repeatTag; | ||
isCancel(err: MiddleResponseError): Boolean; | ||
getUri(config: AxiosRequestConfig): string; | ||
spread(fn: spreadCallback): (array: unknown[]) => any; | ||
all(...args: unknown[]): Promise<unknown[]>; | ||
cancelAll(): void; | ||
cancelFilter(cancelConfigs: Array<CancelConfig>): Array<CancelConfig>; | ||
cancelAutoRetry(err: MiddleResponseError): void; | ||
constructor(); | ||
} | ||
export declare const SugarStatic: AxiosSugarStatic; | ||
export {}; |
@@ -1,4 +0,21 @@ | ||
import { AxiosRequestConfig } from '../vendor/axios'; | ||
export declare function normalizeProp(config: AxiosRequestConfig, prop?: string): AxiosRequestConfig; | ||
export declare function genSymbol(config: AxiosRequestConfig): string; | ||
export declare function capitalize(str: string): string; | ||
export declare function isDef(value: any): boolean; | ||
export declare function isStr(value: any): boolean; | ||
export declare function isError(value: any): boolean; | ||
export declare function getDurationMS(a: number, b: number): number; | ||
export declare function notUndef<T = any, D = any>(targetVal: T, defaultVal: D): T | D; | ||
export declare function log(msg: string): void; | ||
export declare function warn(msg: string): void; | ||
export declare function error(msg: string): void; | ||
export declare function throwError(msg: string): void; | ||
export declare function isDev(): boolean; | ||
export declare function isFn(val: any): boolean; | ||
export declare function isNum(val: any): boolean; | ||
export declare function isPlainObject(val: any): boolean; | ||
export declare function deepMerge(...args: any[]): any; | ||
export declare function merge(...args: any[]): any; | ||
interface onlineOptions { | ||
timeout?: number; | ||
} | ||
export declare function isOnline(options?: onlineOptions): boolean; | ||
export {}; |
@@ -1,6 +0,9 @@ | ||
import { factory } from './core/AxiosSugar'; | ||
import { AxiosSugarStorage, AxiosSugarInnerStorage, AxiosSugarLocalStorage, AxiosSugarInnerReleaseStorage } from './AxiosSugarStorage'; | ||
import AxiosSugarConfig from './AxiosSugarConfig'; | ||
import AxiosSugarLifeCycle from './AxiosSugarLifeCycle'; | ||
export default factory; | ||
export { AxiosSugarStorage, AxiosSugarLifeCycle, AxiosSugarInnerStorage, AxiosSugarLocalStorage, AxiosSugarInnerReleaseStorage, AxiosSugarConfig, }; | ||
import { SugarStatic, AxiosSugar } from './core/AxiosSugar'; | ||
import HttpStatusProcessor from './core/HttpStatusProcessor'; | ||
import { AxiosSugarInnerStorage, AxiosSugarLocalStorage } from './core/AxiosSugarStorage'; | ||
export default SugarStatic; | ||
declare const storage: { | ||
inner: typeof AxiosSugarInnerStorage; | ||
local: typeof AxiosSugarLocalStorage; | ||
}; | ||
export { HttpStatusProcessor, AxiosSugar, storage }; |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
766701
17
89
3030
2
2
63
3
1
+ Addedaxios@^0.19.2
+ Addedobject-sizeof@^1.6.1
+ Addedaxios@0.19.2(transitive)
+ Addedbase64-js@1.5.1(transitive)
+ Addedbuffer@5.7.1(transitive)
+ Addedfollow-redirects@1.5.10(transitive)
+ Addedieee754@1.2.1(transitive)
+ Addedobject-sizeof@1.6.3(transitive)