@croct/plug-react
Version:
React components and hooks to plug your React applications into Croct.
65 lines (64 loc) • 1.57 kB
JavaScript
class Cache {
constructor(defaultExpiration) {
this.cache = {};
this.defaultExpiration = defaultExpiration;
}
load(configuration) {
const { cacheKey, loader, fallback, expiration = this.defaultExpiration } = configuration;
const cachedEntry = this.get(cacheKey);
if (cachedEntry !== void 0) {
if (cachedEntry.error !== void 0) {
if (fallback !== void 0) {
return fallback;
}
if (cachedEntry.result === void 0) {
throw cachedEntry.error;
}
}
if (cachedEntry.result !== void 0) {
return cachedEntry.result;
}
throw cachedEntry.promise;
}
const entry = {
dispose: () => {
if (entry.timeout !== void 0 || expiration < 0) {
return;
}
entry.timeout = window.setTimeout(
() => {
delete this.cache[cacheKey];
},
expiration
);
},
promise: loader().then((result) => {
entry.result = result;
return result;
}).catch((error) => {
entry.result = fallback;
entry.error = error;
return fallback;
}).finally(() => {
entry.dispose();
})
};
this.cache[cacheKey] = entry;
throw entry.promise;
}
get(cacheKey) {
const entry = this.cache[cacheKey];
if (entry === void 0) {
return void 0;
}
if (entry.timeout !== void 0) {
clearTimeout(entry.timeout);
delete entry.timeout;
entry.dispose();
}
return entry;
}
}
export {
Cache
};