Skip to content

Commit

Permalink
Validate shape of cacheMap on initialization (#86)
Browse files Browse the repository at this point in the history
* Validate shape of cacheMap on initialization

* Follow up review:

* Functions should avoid being defined within another function body if possible
* Naming consistency
* Flow typing
* Arrow functions with a single return statement should not use block format
* Check typeof 'function' instead of non-falsey
* filter(Boolean) to remove falsey values

* Update abuse-test.js

* map().filter() can be replaced by .filter()

* 80ch

* Flow
  • Loading branch information
Sid Sethupathi authored and leebyron committed Oct 19, 2017
1 parent a98c896 commit dc3f0cd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
13 changes: 13 additions & 0 deletions src/__tests__/abuse-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,17 @@ describe('Provides descriptive error messages for API abuse', () => {
);
});

it('Cache should have get, set, delete, and clear methods', async () => {
class IncompleteMap {
get() {}
}

expect(() => {
var incompleteMap = new IncompleteMap();
var options = { cacheMap: incompleteMap };
new DataLoader(keys => keys, options); // eslint-disable-line no-new
}).to.throw(
'Custom cacheMap missing methods: set, delete, clear'
);
});
});
21 changes: 19 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ export default class DataLoader<K, V> {
}
this._batchLoadFn = batchLoadFn;
this._options = options;
this._promiseCache =
options && options.cacheMap || (new Map(): Map<K,Promise<V>>);
this._promiseCache = getValidCacheMap(options);
this._queue = [];
}

Expand Down Expand Up @@ -306,6 +305,24 @@ function failedDispatch<K, V>(
});
}

function getValidCacheMap<K, V>(
options: ?Options<K, V>
): CacheMap<K, Promise<V>> {
var cacheMap = options && options.cacheMap;
if (!cacheMap) {
return new Map();
}
var cacheFunctions = [ 'get', 'set', 'delete', 'clear' ];
var missingFunctions = cacheFunctions
.filter(fnName => cacheMap && typeof cacheMap[fnName] !== 'function');
if (missingFunctions.length !== 0) {
throw new TypeError(
'Custom cacheMap missing methods: ' + missingFunctions.join(', ')
);
}
return cacheMap;
}

// Private
type LoaderQueue<K, V> = Array<{
key: K;
Expand Down

0 comments on commit dc3f0cd

Please sign in to comment.