Skip to content

Commit

Permalink
Fix/cache before set (#750)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicholasio authored Apr 17, 2024
1 parent 29d45a2 commit 38563cf
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 3 deletions.
6 changes: 6 additions & 0 deletions .changeset/witty-swans-tap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@headstartwp/core": patch
"@headstartwp/next": patch
---

Fix cache.beforeSet
42 changes: 42 additions & 0 deletions packages/next/src/data/server/__tests__/fetchHookDataa-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { enableFetchMocks } from 'jest-fetch-mock';
import { HeadlessConfig, setHeadstartWPConfig } from '@headstartwp/core';

import { usePosts } from '../../hooks/usePosts';
import { usePost } from '../../hooks/usePost';

import { fetchHookData } from '../fetchHookData';
import cache from '../cache';
Expand Down Expand Up @@ -125,4 +126,45 @@ describe('fetchHookData caching', () => {
expect(config.cache.beforeSet).toHaveBeenCalledTimes(1);
expect(result.data.isCached).toBe(true);
});

it('caches with beforeSet without mutating the fetched data', async () => {
const config = {
useWordPressPlugin: true,
cache: {
enabled: true,

afterGet: async (options, data) => {
return data;
},

beforeSet: async (options, data) => {
return {
...data,
result: {
...data.result,
beforeSetField: true,
},
};
},

cacheHandler: {
set: async (key, data, ttl) => {
cache.set(key, data, ttl);
},
get: async (key) => {
return cache.get(key);
},
},
},
} satisfies HeadlessConfig;

setHeadstartWPConfig(config);

fetchMock.mockResponseOnce(JSON.stringify([{ id: 10 }]));

const result = await fetchHookData(usePost.fetcher(), {}, { params: { slug: 'test3' } });

expect(result.data.result.id).toBe(10);
expect(result.data.result.beforeSetField).toBeUndefined();
});
});
8 changes: 5 additions & 3 deletions packages/next/src/data/server/fetchHookData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ export async function fetchHookData<T = unknown, P extends EndpointParams = Endp
}

if (typeof cache.beforeSet === 'function') {
data = await cache.beforeSet(
const beforeSetData = await cache.beforeSet(
{
fetchStrategy,
params,
Expand All @@ -275,9 +275,11 @@ export async function fetchHookData<T = unknown, P extends EndpointParams = Endp
},
data,
);
}

await cache.cacheHandler.set(cacheKey, data, cache.ttl);
await cache.cacheHandler.set(cacheKey, beforeSetData, cache.ttl);
} else {
await cache.cacheHandler.set(cacheKey, data, cache.ttl);
}
}
} else {
data.isCached = true;
Expand Down

0 comments on commit 38563cf

Please sign in to comment.