Skip to content
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
20 changes: 20 additions & 0 deletions packages/cache/src/fetchwithcache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
7 changes: 7 additions & 0 deletions packages/cache/src/fetchwithcache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down