Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
38 changes: 38 additions & 0 deletions packages/cache/src/main.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Buffer } from 'node:buffer'

import { describe, test, expect } from 'vitest'

import { NetlifyCacheStorage } from './bootstrap/cachestorage.js'
import { caches } from './main.js'
import { getMockFetch } from './test/fetch.js'

const base64Encode = (input: string) => Buffer.from(input, 'utf8').toString('base64')
const host = 'host.netlify'
const url = 'https://example.netlify/.netlify/cache'
const token = 'mock-token'

describe('`caches` export', () => {
test('Provides a no-op cache implementation', async () => {
const html = '<h1>Hello world</h1>'
const mockFetch = getMockFetch({
responses: {
'https://example.netlify/.netlify/cache/https%3A%2F%2Fnetlify.com%2F': [new Response(html)],
},
})
const cache1 = await caches.open('cache1')
const res1 = await cache1.match('https://netlify.com')
expect(res1).toBeUndefined()

globalThis.caches = new NetlifyCacheStorage({
base64Encode,
getContext: () => ({ host, token, url }),
})

const cache2 = await globalThis.caches.open('cache2')
const res2 = await cache2.match('https://netlify.com')
expect(res2?.status).toBe(200)
expect(await res2?.text()).toBe(html)

mockFetch.restore()
})
})
1 change: 1 addition & 0 deletions packages/cache/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { caches } from './polyfill.js'
export { setCacheHeaders } from './cache-headers/cache-headers.js'
export { getCacheStatus } from './cache-status/cache-status.js'
export { fetchWithCache } from './fetchwithcache.js'
Expand Down
13 changes: 13 additions & 0 deletions packages/cache/src/polyfill.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { NetlifyCacheStorage } from './bootstrap/cachestorage.js'

/**
* Polyfill for local development environments where `globalThis.caches` is not
* available. This is a no-op cache, which will automatically work with the
* real one in production.
*/
export const caches =
globalThis.caches ??
new NetlifyCacheStorage({
base64Encode: () => '',
getContext: () => null,
})
Loading