@kwiz/node
Version:
KWIZ utilities and helpers for node applications
43 lines • 1.97 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getWithCache = void 0;
const common_1 = require("@kwiz/common");
const $$cache = {};
function getWithCache(worker, info) {
return __awaiter(this, void 0, void 0, function* () {
const now = new Date();
//purge old values
Object.keys($$cache).forEach(key => {
if ($$cache[key].expires < now)
delete $$cache[key];
});
let cached = info.forceRefresh ? null : $$cache[info.cacheKey];
if ((0, common_1.isNullOrUndefined)(cached)) {
const result = yield worker();
if (result.success) {
$$cache[info.cacheKey] = {
expires: new Date(new Date().getTime() + info.successCacheDuration * 1000),
value: result.value
};
}
else if (info.failedCacheDuration > 0) {
$$cache[info.cacheKey] = {
expires: new Date(new Date().getTime() + info.failedCacheDuration * 1000),
value: result.value
};
}
}
return $$cache[info.cacheKey].value;
});
}
exports.getWithCache = getWithCache;
//# sourceMappingURL=get-with-cache.js.map