Skip to content

Instantly share code, notes, and snippets.

@ryanspradlin
Last active September 28, 2018 16:02
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanspradlin/1e951a4dcf737e3fb194 to your computer and use it in GitHub Desktop.
Save ryanspradlin/1e951a4dcf737e3fb194 to your computer and use it in GitHub Desktop.
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
Copy link

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