Skip to content

Commit 38fedd4

Browse files
authored
perf: call cacheKeyFn only when it is needed (if caching) (#342)
* perf: call and reuse cacheKeyFn only when it is needed (if caching) * test: add a test case for cacheKeyFn not being called * chore: fix flow error * docs: add changeset
1 parent 18da9f3 commit 38fedd4

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

.changeset/smooth-crabs-lie.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'dataloader': patch
3+
---
4+
5+
Ensure `cacheKeyFn` is not called when caching is disabled, since the key is not utilized in that case.

src/__tests__/dataloader.test.js

+14
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,20 @@ describe('Accepts options', () => {
750750
expect(cacheMap.get('X')).toBe(promiseX);
751751
});
752752

753+
it('Does not call cacheKeyFn when cache is disabled', async () => {
754+
const cacheKeyFnCalls = [];
755+
const [identityLoader] = idLoader<string>({
756+
cache: false,
757+
cacheKeyFn: key => {
758+
cacheKeyFnCalls.push(key);
759+
return key;
760+
},
761+
});
762+
763+
await identityLoader.load('A');
764+
expect(cacheKeyFnCalls).toEqual([]);
765+
});
766+
753767
it('Complex cache behavior via clearAll()', async () => {
754768
// This loader clears its cache as soon as a batch function is dispatched.
755769
const loadCalls = [];

src/index.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,11 @@ class DataLoader<K, V, C = K> {
8181

8282
const batch = getCurrentBatch(this);
8383
const cacheMap = this._cacheMap;
84-
const cacheKey = this._cacheKeyFn(key);
84+
let cacheKey: ?C;
8585

8686
// If caching and there is a cache-hit, return cached Promise.
8787
if (cacheMap) {
88+
cacheKey = this._cacheKeyFn(key);
8889
const cachedPromise = cacheMap.get(cacheKey);
8990
if (cachedPromise) {
9091
const cacheHits = batch.cacheHits || (batch.cacheHits = []);
@@ -105,7 +106,7 @@ class DataLoader<K, V, C = K> {
105106

106107
// If caching, cache this promise.
107108
if (cacheMap) {
108-
cacheMap.set(cacheKey, promise);
109+
cacheMap.set((cacheKey: any), promise);
109110
}
110111

111112
return promise;

0 commit comments

Comments
 (0)