diff --git a/packages/cache/src/fetchwithcache.test.ts b/packages/cache/src/fetchwithcache.test.ts index 555c712c..4062fe48 100644 --- a/packages/cache/src/fetchwithcache.test.ts +++ b/packages/cache/src/fetchwithcache.test.ts @@ -307,4 +307,24 @@ describe('`fetchWithCache`', () => { mockFetch.restore() expect(mockFetch.fulfilled).toBe(true) }) + + test('Accepts a custom `fetch` implementation', async () => { + const mockFetch = new MockFetch() + .get({ + url: 'https://example.netlify/.netlify/cache/https%3A%2F%2Fnetlify.com%2F', + response: new Response(null, { status: 404 }), + }) + .post({ + url: 'https://example.netlify/.netlify/cache/https%3A%2F%2Fnetlify.com%2F', + response: new Response(null, { status: 201 }), + }) + .inject() + const customFetch: typeof globalThis.fetch = async () => new Response('rijwiel') + + const response = await fetchWithCache('https://netlify.com', { fetch: customFetch }) + expect(await response.text()).toBe('rijwiel') + + mockFetch.restore() + expect(mockFetch.fulfilled).toBe(true) + }) }) diff --git a/packages/cache/src/fetchwithcache.ts b/packages/cache/src/fetchwithcache.ts index 77f7b3f4..ae50c6fa 100644 --- a/packages/cache/src/fetchwithcache.ts +++ b/packages/cache/src/fetchwithcache.ts @@ -31,6 +31,11 @@ type CacheOptions = CacheSettings & { */ cache?: NetlifyCache | string + /** + * A custom `fetch` implementation to be used instead of the native one. + */ + fetch?: typeof globalThis.fetch + /** * When `fetchWithCache` fetches a new response and adds it to the cache, the * `Promise` it returns waits for both the network call to finish and for the @@ -115,6 +120,8 @@ export const fetchWithCache: FetchWithCache = async ( return cached } + const { fetch = globalThis.fetch } = cacheOptions + const fresh = await fetch(request) if (!fresh.body) { return fresh