axios-retryer
Version:
axios-retryer is an advanced Axios request manager offering intelligent retry logic with token refresh, concurrency control, priority queuing, and a flexible plugin architecture, all built with TypeScript for robust HTTP client integrations.
2 lines (1 loc) • 6.63 kB
JavaScript
"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};function t(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))}function n(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function r(e,t,n){if(n||2===arguments.length)for(var r,i=0,a=t.length;i<a;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var i=function(){function i(t){this.name="CachingPlugin",this.version="1.0.0",this.interceptorIdReq=null,this.interceptorIdRes=null,this.cache=new Map,this.cacheLock=new Map,this.cleanupTimer=null,this.options=e({compareHeaders:!1,timeToRevalidate:0,cacheMethods:["GET"],cleanupInterval:0,maxAge:0,maxItems:1e3,cacheOnlyRetriedRequests:!1},t)}return i.prototype.initialize=function(e){var t=this;this.manager=e;var n=e.axiosInstance;this.interceptorIdReq=n.interceptors.request.use((function(e){return t.handleRequest(e)}),(function(e){return Promise.reject(e)})),this.interceptorIdRes=n.interceptors.response.use((function(e){return t.handleResponseSuccess(e)}),(function(e){return Promise.reject(e)})),this.options.cleanupInterval>0&&this.startPeriodicCleanup()},i.prototype.onBeforeDestroyed=function(){null!==this.interceptorIdReq&&this.manager.axiosInstance.interceptors.request.eject(this.interceptorIdReq),null!==this.interceptorIdRes&&this.manager.axiosInstance.interceptors.response.eject(this.interceptorIdRes),this.stopPeriodicCleanup()},i.prototype.handleRequest=function(t){var n,r,i=(t.method||"GET").toUpperCase();if(!this.options.cacheMethods.includes(i))return t;if(this.options.cacheOnlyRetriedRequests&&!t.__isRetrying)return t;var a=this.generateCacheKey(t),o=this.cache.get(a);if(o){var s=Date.now()-o.timestamp;if(0===this.options.timeToRevalidate||s<this.options.timeToRevalidate)return null===(n=this.manager.getLogger())||void 0===n||n.debug("[CachingPlugin] Cache hit for ".concat(a," (age: ").concat(s,"ms)")),e(e({},t),{adapter:function(){return Promise.resolve(e(e({},o.response),{config:t}))}});null===(r=this.manager.getLogger())||void 0===r||r.debug("[CachingPlugin] Cache stale for ".concat(a," (age: ").concat(s,"ms); removing entry.")),this.cache.delete(a)}return t},i.prototype.handleResponseSuccess=function(e){return t(this,void 0,void 0,(function(){var t,r,i,a;return n(this,(function(n){switch(n.label){case 0:if(this.options.cacheOnlyRetriedRequests&&e.config&&!e.config.__isRetrying)return[2,e];if(!(e.status>=200&&e.status<300))return[3,4];t=this.generateCacheKey(e.config),(r=this.cacheLock.get(t))||(r=Promise.resolve(),this.cacheLock.set(t,r)),n.label=1;case 1:return n.trys.push([1,,3,4]),[4,r];case 2:return n.sent(),this.options.maxItems>0&&this.cache.size>=this.options.maxItems&&(i=Array.from(this.cache.entries()).sort((function(e,t){var n=e[1],r=t[1];return n.timestamp-r.timestamp}))[0][0],this.cache.delete(i)),null===(a=this.manager.getLogger())||void 0===a||a.debug("[CachingPlugin] Caching response for ".concat(t)),this.cache.set(t,{response:e,timestamp:Date.now()}),[3,4];case 3:return this.cacheLock.delete(t),[7];case 4:return[2,e]}}))}))},i.prototype.generateCacheKey=function(e){if(!e.url)throw new Error("URL is required for cache key generation");var t=(e.method||"GET").toUpperCase(),n=e.params?"object"==typeof e.params?JSON.stringify(e.params):String(e.params):"",r=e.data?"object"==typeof e.data?JSON.stringify(e.data):String(e.data):"",i="";return this.options.compareHeaders&&e.headers&&(i="object"==typeof e.headers?JSON.stringify(e.headers):String(e.headers)),[t,e.url,n,r,i].join("|")},i.prototype.startPeriodicCleanup=function(){var e=this;this.cleanupTimer||(this.cleanupTimer=setInterval((function(){e.runCacheCleanup()}),this.options.cleanupInterval))},i.prototype.stopPeriodicCleanup=function(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)},i.prototype.runCacheCleanup=function(){var e,t=this,n=Date.now(),i=[];if(this.options.maxAge>0)for(var a=0,o=this.cache.entries();a<o.length;a++){var s=o[a],c=s[0];n-s[1].timestamp>this.options.maxAge&&i.push(c)}if(this.options.maxItems>0&&this.cache.size>this.options.maxItems){var u=Array.from(this.cache.entries()).sort((function(e,t){var n=e[1],r=t[1];return n.timestamp-r.timestamp})),h=u.slice(0,this.cache.size-this.options.maxItems).map((function(e){return e[0]}));i=r([],new Set(r(r([],i,!0),h,!0)),!0)}i.length>0&&(i.forEach((function(e){return t.cache.delete(e)})),null===(e=this.manager.getLogger())||void 0===e||e.debug("[CachingPlugin] Cleaned up ".concat(i.length," cached items")))},i.prototype.clearCache=function(){var e;this.cache.clear(),null===(e=this.manager.getLogger())||void 0===e||e.debug("[CachingPlugin] Cache cleared.")},i.prototype.getCacheStats=function(){var e=Date.now(),t=Array.from(this.cache.values());if(0===t.length)return{size:0,oldestItemAge:0,newestItemAge:0,averageAge:0};var n=t.map((function(t){return e-t.timestamp}));return{size:this.cache.size,oldestItemAge:Math.max.apply(Math,n),newestItemAge:Math.min.apply(Math,n),averageAge:n.reduce((function(e,t){return e+t}),0)/n.length}},i}();exports.CachingPlugin=i;