batchloader
Version:
BatchLoader is a utility for data fetching layer to reduce requests via batching written in TypeScript. Inspired by Facebook's DataLoader
58 lines • 1.59 kB
JavaScript
import { MappedBatchLoader } from './mappedbatchloader';
export class CacheLoader {
constructor(loader, cache = new Map()) {
this.loader = loader;
this.cache = cache;
this.promiseCache = new Map();
}
load(key) {
const { promiseCache } = this;
let pv = promiseCache.get(key);
if (pv) {
return pv;
}
const value = this.cache.get(key);
pv =
value === undefined
? this.loader.load(key).then((val) => {
this.set(key, val);
return val;
})
: Promise.resolve(value);
promiseCache.set(key, pv);
return pv;
}
loadMany(keys) {
return Promise.all(keys.map((key) => this.load(key)));
}
mapLoader(mapFn) {
return new MappedBatchLoader(this, mapFn);
}
get(key) {
let pv = this.promiseCache.get(key);
if (pv) {
return pv;
}
const v = this.cache.get(key);
if (v === undefined) {
return undefined;
}
pv = Promise.resolve(v);
this.promiseCache.set(key, pv);
return pv;
}
set(key, value) {
this.promiseCache.delete(key);
this.cache.set(key, value);
}
delete(key) {
const pDeleted = this.promiseCache.delete(key);
const deleted = this.cache.delete(key);
return pDeleted || deleted;
}
clear() {
this.promiseCache.clear();
this.cache.clear();
}
}
//# sourceMappingURL=cacheloader.js.map