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.
124 lines (123 loc) • 2.48 kB
JavaScript
/*! idmp v0.0.0 | (c) github/haozi | MIT */
var y = (a, s, r) => new Promise((i, c) => {
var f = (n) => {
try {
e(r.next(n));
} catch (o) {
c(o);
}
}, t = (n) => {
try {
e(r.throw(n));
} catch (o) {
c(o);
}
}, e = (n) => n.done ? i(n.value) : Promise.resolve(n.value).then(f, t);
e((r = r.apply(a, s)).next());
});
/*! idmp v3.4.4 | (c) github/haozi | MIT */
const h = () => {
}, m = (a) => a < 0 ? 0 : a > 6048e5 ? 6048e5 : a, E = (a) => {
const {
maxRetry: s = 30,
maxAge: r = 3e3,
minRetryDelay: i = 50,
maxRetryDelay: c = 5e3,
onBeforeRetry: f = h,
signal: t
} = a || {}, e = m(r);
return {
maxRetry: s,
maxAge: e,
minRetryDelay: i,
maxRetryDelay: c,
onBeforeRetry: f,
f: r === 1 / 0,
// Infinity
signal: t
};
};
const D = "@idmp/v1/", u = (a) => `${D}${a}`, A = (a) => {
let s;
try {
s = window[a];
} catch (t) {
}
const r = (t) => {
if (t)
try {
const e = u(t);
s.removeItem(e);
} catch (e) {
}
};
return {
get: (t) => {
if (!t) return;
const e = u(t);
let n;
try {
if (n = JSON.parse(s.getItem(e) || ""), n === void 0) return;
const { t: o, a: l, d: g } = n;
if (Date.now() - o > l) {
r(e);
return;
}
return g;
} catch (o) {
}
},
set: (t, e, n) => {
if (!t) return;
const o = u(t);
try {
s.setItem(
o,
JSON.stringify({
t: Date.now(),
// timestamp
a: n,
// age (ttl)
d: e
// data
})
);
} catch (l) {
}
},
remove: r,
clear: () => {
try {
for (let t = s.length - 1; t >= 0; t--) {
const e = s.key(t);
e && e.startsWith(D) && r(e);
}
} catch (t) {
}
}
};
}, I = (a, s = "sessionStorage") => {
const r = A(s), i = (c, f, t) => {
const e = E(t);
return a(
c,
() => y(null, null, function* () {
const n = r.get(c);
if (n !== void 0)
return n;
const o = yield f();
return o !== void 0 && r.set(c, o, e.maxAge), o;
}),
t
);
};
return i.flush = (c) => {
a.flush(c), r.remove(c);
}, i.flushAll = () => {
a.flushAll(), r.clear();
}, i;
};
export {
I as default,
u as getCacheKey
};