@hhgtech/hhg-components
Version:
Hello Health Group common components
56 lines (53 loc) • 1.98 kB
JavaScript
import { a as __awaiter } from './tslib.es6-00ab44b2.js';
import { isProduction } from './constantsIsProduction.js';
const ServerCache = {};
const getCachedItem = (key) => {
if (typeof window !== 'undefined') {
let res;
try {
res = JSON.parse(localStorage.getItem((!isProduction ? 'staging_' : '') + 'hhg-cache-' + key) || '{}');
}
catch (_a) { }
return res || {};
}
else {
return ServerCache[key];
}
};
const setCachedItem = (key, value) => {
try {
if (typeof window !== 'undefined') {
localStorage.setItem((!isProduction ? 'staging_' : '') + 'hhg-cache-' + key, JSON.stringify({ data: value, time: Date.now() }));
}
else {
ServerCache[key] = { data: value, time: Date.now() };
}
}
catch (_a) { }
};
const getDataWithCache = (key, dataGetter, validator, cacheTime = 1000 * 60 * 15) => __awaiter(void 0, void 0, void 0, function* () {
const persistData = getCachedItem(key);
if (!!(persistData === null || persistData === void 0 ? void 0 : persistData.data)) {
// if expired, still return data first then refetch for next time
setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
if (persistData.time && Date.now() - persistData.time > cacheTime) {
if (dataGetter) {
const data = yield dataGetter();
if (!validator || validator(data)) {
setCachedItem(key, data);
}
}
}
}), 0);
return persistData.data;
}
else if (dataGetter) {
const data = yield dataGetter();
if (!validator || validator(data)) {
setCachedItem(key, data);
}
return data;
}
return null;
});
export { getCachedItem as a, getDataWithCache as g, setCachedItem as s };