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 15, 2017
1 parent c7f047e commit bdf8e0b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/__tests__/abuse-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,23 @@ describe('Provides descriptive error messages for API abuse', () => {
);
});

it('Cache should have get, set, delete, and clear methods', async () => {
class IncompleteMap {
get(key) {
return this.stash[key];
}
}

expect(() => {
var incompleteMap = new IncompleteMap();
var options = { cacheMap: incompleteMap };
new DataLoader( // eslint-disable-line no-new
keys => Promise.resolve(keys),
options
);
}).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 bdf8e0b

Please sign in to comment.