@croct/cache
Version:
An abstraction layer for caching.
43 lines (42 loc) • 1.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HoldWhileRevalidateCache = void 0;
const time_1 = require("@croct/time");
const defaultClockProvider_1 = require("@croct/time/defaultClockProvider");
class HoldWhileRevalidateCache {
constructor({ cacheProvider, maxAge, clock }) {
this.cacheProvider = cacheProvider;
this.maxAge = maxAge;
this.clock = clock ?? defaultClockProvider_1.DefaultClockProvider.getClock();
}
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);
const maxAge = typeof this.maxAge === 'function'
? this.maxAge(key, possiblyStaleEntry.value)
: this.maxAge;
if (now.isAfter(possiblyStaleEntry.timestamp.plusSeconds(maxAge))) {
const entry = await retrieveAndSave();
return entry.value;
}
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.HoldWhileRevalidateCache = HoldWhileRevalidateCache;