@croct/plug-react
Version:
React components and hooks to plug your React applications into Croct.
89 lines (88 loc) • 2.57 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var Cache_exports = {};
__export(Cache_exports, {
Cache: () => Cache
});
module.exports = __toCommonJS(Cache_exports);
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;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Cache
});