@hhgtech/hhg-components
Version:
Hello Health Group common components
60 lines (56 loc) • 2.11 kB
JavaScript
;
var tslib_es6 = require('./tslib.es6-92cccef3.js');
var constantsIsProduction = require('./constantsIsProduction.js');
const ServerCache = {};
const getCachedItem = (key) => {
if (typeof window !== 'undefined') {
let res;
try {
res = JSON.parse(localStorage.getItem((!constantsIsProduction.isProduction ? 'staging_' : '') + 'hhg-cache-' + key) || '{}');
}
catch (_a) { }
return res || {};
}
else {
return ServerCache[key];
}
};
const setCachedItem = (key, value) => {
try {
if (typeof window !== 'undefined') {
localStorage.setItem((!constantsIsProduction.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) => tslib_es6.__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(() => tslib_es6.__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;
});
exports.getCachedItem = getCachedItem;
exports.getDataWithCache = getDataWithCache;
exports.setCachedItem = setCachedItem;