Skip to content

Commit 6eff819

Browse files
feat: add fetch parameter to fetchWithCache (#482)
* feat: add `fetch` parameter to `fetchWithCache` * chore: update test
1 parent 33ab437 commit 6eff819

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

packages/cache/src/fetchwithcache.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,4 +307,24 @@ describe('`fetchWithCache`', () => {
307307
mockFetch.restore()
308308
expect(mockFetch.fulfilled).toBe(true)
309309
})
310+
311+
test('Accepts a custom `fetch` implementation', async () => {
312+
const mockFetch = new MockFetch()
313+
.get({
314+
url: 'https://example.netlify/.netlify/cache/https%3A%2F%2Fnetlify.com%2F',
315+
response: new Response(null, { status: 404 }),
316+
})
317+
.post({
318+
url: 'https://example.netlify/.netlify/cache/https%3A%2F%2Fnetlify.com%2F',
319+
response: new Response(null, { status: 201 }),
320+
})
321+
.inject()
322+
const customFetch: typeof globalThis.fetch = async () => new Response('rijwiel')
323+
324+
const response = await fetchWithCache('https://netlify.com', { fetch: customFetch })
325+
expect(await response.text()).toBe('rijwiel')
326+
327+
mockFetch.restore()
328+
expect(mockFetch.fulfilled).toBe(true)
329+
})
310330
})

packages/cache/src/fetchwithcache.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ type CacheOptions = CacheSettings & {
3131
*/
3232
cache?: NetlifyCache | string
3333

34+
/**
35+
* A custom `fetch` implementation to be used instead of the native one.
36+
*/
37+
fetch?: typeof globalThis.fetch
38+
3439
/**
3540
* When `fetchWithCache` fetches a new response and adds it to the cache, the
3641
* `Promise` it returns waits for both the network call to finish and for the
@@ -115,6 +120,8 @@ export const fetchWithCache: FetchWithCache = async (
115120
return cached
116121
}
117122

123+
const { fetch = globalThis.fetch } = cacheOptions
124+
118125
const fresh = await fetch(request)
119126
if (!fresh.body) {
120127
return fresh

0 commit comments

Comments
 (0)