@croct/cache
Version:
An abstraction layer for caching.
41 lines (40 loc) • 1.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.StaleWhileRevalidateCache = void 0;
const time_1 = require("@croct/time");
const defaultClockProvider_1 = require("@croct/time/defaultClockProvider");
class StaleWhileRevalidateCache {
constructor(config) {
this.cacheProvider = config.cacheProvider;
this.freshPeriod = config.freshPeriod;
this.clock = config.clock ?? defaultClockProvider_1.DefaultClockProvider.getClock();
this.errorHandler = config.errorHandler ?? (() => { });
}
async get(key, loader) {
const now = time_1.Instant.now(this.clock);
const retrieveAndSave = async () => {
const entry = {
value: await loader(key),
timestamp: now,
};
await this.cacheProvider.set(key, entry);
return entry;
};
const possiblyStaleEntry = await this.cacheProvider.get(key, retrieveAndSave);
if (now.isAfter(possiblyStaleEntry.timestamp.plusSeconds(this.freshPeriod))) {
// If expired revalidate on the background and return cached value
retrieveAndSave().catch(this.errorHandler);
}
return possiblyStaleEntry.value;
}
set(key, value) {
return this.cacheProvider.set(key, {
value: value,
timestamp: time_1.Instant.now(this.clock),
});
}
delete(key) {
return this.cacheProvider.delete(key);
}
}
exports.StaleWhileRevalidateCache = StaleWhileRevalidateCache;