Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
type BatchLoadFn<K, V> = (keys: Array<K>) => Promise<Array<V | Error>>;
type LoadAllFn<K, V> = () => Promise<Array<[K, V]>>;
type Options<K, V> = {
batch?: boolean,
cache?: boolean,
cacheMap?: CacheMap<K, Promise<V>>,
cacheKeyFn?: (key: any) => any
};
class AllDataLoader<K, V> extends DataLoader<K, V> {
_loadAllFn: LoadAllFn<K, V>;
_shouldCache: boolean;
_trackedKeys: Array<K>;
constructor(
batchLoadFn: BatchLoadFn<K, V>,
loadAllFn: LoadAllFn<K, V>,
options?: Options<K, V>) {
super(batchLoadFn, options);
this._loadAllFn = loadAllFn;
this._shouldCache = !options || options.cache !== false;
this._trackedKeys = [];
}
async loadAll(): Promise<Array<V>> {
if (this._shouldCache && this._trackedKeys.length > 0) {
return super.loadMany(this._trackedKeys);
}
const entries = await this._loadAllFn();
const keys = new Array(entries.length);
const values = new Array(entries.length);
entries.forEach(
([key, value], index) => {
super.prime(key, value);
keys[index] = key;
values[index] = value;
}
);
this._trackedKeys = keys;
return values;
}
clear(key: K): AllDataLoader<K, V> {
super.clear(key);
return this;
}
clearAll(): AllDataLoader<K, V> {
this._trackedKeys = [];
super.clearAll();
return this;
}
}
@eladchen

This comment has been minimized.

Copy link

@eladchen eladchen commented Sep 28, 2018

Hi,

This looks like a good solution, but I'm not sure I understand what is going on.

type LoadAllFn<K, V> = () => Promise<Array<[K, V]>>;

is the above equivalent to

type LoadAllFn<K, V> = () => Promise<Array<Array<K, V>>>;

either way, this reads to me "An array of array with a key & value?" How is that possible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment