UNPKG

@iel/axios-ext-cancel-repeat

Version:

Cancel repeat request of axios.

10 lines (9 loc) 2.35 kB
/*! * @iel/axios-ext-cancel-repeat v1.1.0 * Cancel repeat request of axios. * * https://github.com/iel-h/axios-ext * * Licensed under the MIT license. */ import{getKeyByConfig as I,createShallowAxiosInstance as d,EVENT_STORE_KEY as h,onRequest as b,onResponse as M,onResponseError as q,onDestroy as N}from"@iel/axios-ext";import{assignSafely as P,deleteKeys as S,helperCreateEventStoreManager as O,isBoolean as B,isFunction as E,isNullish as f,isString as T,noop as G}from"@iel/axios-ext-utils";import _ from"axios";var K=(o={})=>{let e=P({globalNotAllowRepeat:!1},o);return B(e.globalNotAllowRepeat)||(e.globalNotAllowRepeat=!!e.globalNotAllowRepeat),E(e.keyGenerator)||(e.keyGenerator=void 0),E(e.onRepeat)||(e.onRepeat=G),e},m=(o={})=>{let e=P({key:""},o);return!T(e.key)&&!f(e.key)&&(e.key=String(e.key)),e},V=()=>new Map,D=(o,e)=>{let i=n=>{var a;let c=T(n)?n:I(e.instance,n);return(a=o.get(c))!=null?a:null},u=n=>{if(!!(n!=null&&n.key))return o.set(n.key,n)},r=(n,c=!0)=>{var g;let a=i(n);return a===null?!1:(c&&((g=a.cancel)==null||g.call(a)),o.delete(a.key))},x=(n,c=!0)=>{var t;let a=[],g=!1,s=()=>g=!0;for(let[l,R]of o.entries())if(((t=n(R,l,s))!=null?t:!1)&&a.push(l),g){a=[l];break}return a.map(l=>r(l,E(c)?c(i(l)):c)).every(Boolean)},A=()=>{x(()=>!0)};return{get:i,set:u,remove:r,removeBy:x,clear:A,destroy:()=>{A()}}},F=function(o,e){let i=K(e),u=V(),r=D(u,o),x=O("CancelRepeat"),A=o.instance,y=["notAllowRepeat","allowRepeat","CancelRepeat"],n=function(s){let t=d(o,this);return x.set(t[h],{allowRepeat:!1,args:m(s)}),S(t,y),t},c=function(){let s=d(o,this);return x.set(s[h],{allowRepeat:!0,args:null}),S(s,y),s},a=s=>r.get(s.key)!==null,g=({$eventStore:s})=>{var l;let t=(l=x.get(s))==null?void 0:l.args;f(t)||r.remove(t.key,!1)};A.CancelRepeat=r,A.notAllowRepeat=n,A.allowRepeat=c,b(({$eventStore:s,config:t,setReturnValue:l})=>{var C,k;let R=x.get(s);if(f(R)){if(!i.globalNotAllowRepeat)return;R=x.set(s,{allowRepeat:!1,args:m()})}if(R.allowRepeat)return;let p=R.args;if(p.key||(p.key=(k=(C=i.keyGenerator)==null?void 0:C.call(i,t,p))!=null?k:I(o.instance,t),p.key=String(p.key)),a(p))return l(Promise.resolve(i.onRepeat(t,p)));let w={key:p.key,config:t};r.set(w),t.cancelToken||(t.cancelToken=new _.CancelToken(v=>{r.get(w.key).cancel=()=>v(i.manualCancelMessage)}))}),M(g),q(g),N(()=>{r.destroy()})},$=F;export{$ as default};