UNPKG

idmp

Version:

A lightweight TypeScript library for deduplicating and caching async function calls with automatic retries, designed for idempotent network requests in React and Node.js.

197 lines (196 loc) 3.41 kB
/*! idmp v3.4.4 | (c) github/haozi | MIT */ var E = Math.pow; const M = () => { }; const R = setTimeout, F = (e, s) => e > s ? e : s, L = (e, s) => e < s ? e : s, N = (e) => e < 0 ? 0 : e > 6048e5 ? 6048e5 : e; let i = {}; const U = (e) => { const { maxRetry: s = 30, maxAge: c = 3e3, minRetryDelay: a = 50, maxRetryDelay: u = 5e3, onBeforeRetry: l = M, signal: m } = e || {}, d = N(c); return { maxRetry: s, maxAge: d, minRetryDelay: a, maxRetryDelay: u, onBeforeRetry: l, f: c === 1 / 0, // Infinity signal: m }; }, h = (e) => { e && delete i[e]; }, P = () => { i = {}; }, y = (e, s, c) => { if (!e) return s(); const { maxRetry: a, minRetryDelay: u, maxRetryDelay: l, maxAge: m, onBeforeRetry: d, f: _, signal: f } = U(c); i[e] = i[e] || [ 0, // [K.retryCount]: number 0, // [K.status]: Status [] // [K.pendingList]: Array<any> ]; const t = i[e], x = () => { t[ 1 /* status */ ] = 0, t[ 3 /* resolvedData */ ] = t[ 4 /* rejectionError */ ] = void 0; }, g = () => { const r = t[ 2 /* pendingList */ ].length; for (let n = 0; n < r; ++n) t[ 2 /* pendingList */ ][n][0](t[ 3 /* resolvedData */ ]); t[ 2 /* pendingList */ ] = [], _ || R(() => { h(e); }, m); }, A = () => { const r = t[ 2 /* pendingList */ ].length; let n; n = r - a, (n < 0 || !isFinite(r)) && (n = F(1, t[ 2 /* pendingList */ ].length - 3)); for (let o = 0; o < n; ++o) t[ 2 /* pendingList */ ][o][1](t[ 4 /* rejectionError */ ]); h(e); }, D = () => new Promise((r, n) => { if (!t[ 5 /* cachedPromiseFunc */ ] && (t[ 5 /* cachedPromiseFunc */ ] = s), t[ 3 /* resolvedData */ ]) { r(t[ 3 /* resolvedData */ ]); return; } if (f) { if (f.aborted) return; f.addEventListener("abort", () => { x(), t[ 4 /* rejectionError */ ] = new DOMException( f.reason, "AbortError" ), A(); }); } t[ 1 /* status */ ] === 0 ? (t[ 1 /* status */ ] = 1, t[ 2 /* pendingList */ ].push([r, n]), t[ 5 /* cachedPromiseFunc */ ]().then((o) => { t[ 3 /* resolvedData */ ] = o, g(), t[ 1 /* status */ ] = 4; }).catch((o) => { if (t[ 1 /* status */ ] = 3, t[ 4 /* rejectionError */ ] = o, ++t[ 0 /* retryCount */ ], t[ 0 /* retryCount */ ] > a) A(); else { d(o, { globalKey: e, retryCount: t[ 0 /* retryCount */ ] }), x(); const p = L( l, u * E(2, t[ 0 /* retryCount */ ] - 1) ); R(D, p); } })) : t[ 1 /* status */ ] === 1 && t[ 2 /* pendingList */ ].push([r, n]); }); return D(); }; y.flush = h; y.flushAll = P; export { y as default, U as getOptions, y as idmp };