Skip to content

Commit

Permalink
Validate shape of cacheMap on initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
sidsethupathi committed Jun 16, 2017
1 parent c7f047e commit e323ec6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/__tests__/abuse-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,18 @@ 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 cache needs to implement get, set, delete, and clear methods, ' +
'but missing: set, delete, clear.'
);
});
});
17 changes: 16 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,23 @@ export default class DataLoader<K, V> {
}
this._batchLoadFn = batchLoadFn;
this._options = options;
var validateCacheFormat = cache => {
var cacheFunctions = [ 'get', 'set', 'delete', 'clear' ];
var missingFunctions = cacheFunctions.map(fnName => {
return !cache[fnName] ? fnName : null;
})
.filter(fnName => fnName !== null);

if (missingFunctions.length > 0) {
throw new TypeError('Custom cache needs to implement get, set, ' +
'delete, and clear methods, but missing: ' +
`${missingFunctions.join(', ')}.` );
}
return cache;
};
this._promiseCache =
options && options.cacheMap || (new Map(): Map<K,Promise<V>>);
options && options.cacheMap && validateCacheFormat(options.cacheMap) ||
(new Map(): Map<K,Promise<V>>);
this._queue = [];
}

Expand Down

0 comments on commit e323ec6

Please sign in to comment.