Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

perf: call cacheKeyFn only when it is needed (if caching) #342

Merged
merged 4 commits into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/smooth-crabs-lie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'dataloader': patch
---

Ensure `cacheKeyFn` is not called when caching is disabled, since the key is not utilized in that case.
14 changes: 14 additions & 0 deletions src/__tests__/dataloader.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,20 @@ describe('Accepts options', () => {
expect(cacheMap.get('X')).toBe(promiseX);
});

it('Does not call cacheKeyFn when cache is disabled', async () => {
const cacheKeyFnCalls = [];
const [identityLoader] = idLoader<string>({
cache: false,
cacheKeyFn: key => {
cacheKeyFnCalls.push(key);
return key;
},
});

await identityLoader.load('A');
expect(cacheKeyFnCalls).toEqual([]);
});

it('Complex cache behavior via clearAll()', async () => {
// This loader clears its cache as soon as a batch function is dispatched.
const loadCalls = [];
Expand Down
5 changes: 3 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,11 @@ class DataLoader<K, V, C = K> {

const batch = getCurrentBatch(this);
const cacheMap = this._cacheMap;
const cacheKey = this._cacheKeyFn(key);
let cacheKey: ?C;

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

// If caching, cache this promise.
if (cacheMap) {
cacheMap.set(cacheKey, promise);
cacheMap.set((cacheKey: any), promise);
}

return promise;
Expand Down