diff --git a/README.md b/README.md index 03b012b..7028de4 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,12 @@ The function looks for a `GOOGLE_API_KEY` value using `process.env` in Node or `Deno.env.get` in Netlify's Edge runtime. When the variable is absent, a default API key is used. +### Caching + +Responses are cached for 30 seconds using the Edge Cache API when available. If +the runtime does not support the cache API, the function skips caching but still +returns live data. + ### Running tests ```sh diff --git a/netlify/edge-functions/opensheet.js b/netlify/edge-functions/opensheet.js index d03a26c..681096f 100644 --- a/netlify/edge-functions/opensheet.js +++ b/netlify/edge-functions/opensheet.js @@ -34,13 +34,15 @@ export default async function handler(request, context) { // Try cache first (Edge Cache API) const cacheKey = `https://sheets-json-api.netlify.app/${id}/${encodeURIComponent(sheet)}`; - const cache = caches.default; - const cachedResponse = await cache.match(cacheKey); - if (cachedResponse) { - console.log(`Serving from cache: ${cacheKey}`); - return cachedResponse; - } else { - console.log(`Cache miss: ${cacheKey}`); + const cache = globalThis.caches?.default; + if (cache) { + const cachedResponse = await cache.match(cacheKey); + if (cachedResponse) { + console.log(`Serving from cache: ${cacheKey}`); + return cachedResponse; + } else { + console.log(`Cache miss: ${cacheKey}`); + } } // Normalize sheet (handle '+' and decode) @@ -104,7 +106,9 @@ export default async function handler(request, context) { }); // Write to cache in the background - context.waitUntil(cache.put(cacheKey, apiResponse.clone())); + if (cache) { + context.waitUntil(cache.put(cacheKey, apiResponse.clone())); + } return apiResponse; } diff --git a/test/opensheet.test.js b/test/opensheet.test.js index f30ec06..0b5ce88 100644 --- a/test/opensheet.test.js +++ b/test/opensheet.test.js @@ -40,6 +40,21 @@ test('falls back to static content on root path', async () => { assert.strictEqual(res, nextResponse); }); +test('works when cache API is unavailable', async () => { + delete globalThis.caches; + + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => + new Response(JSON.stringify({ values: [["name"], ["Ada"]] })); + + const req = new Request('https://example.com/test-sheet/Sheet1'); + const res = await handler(req, context); + const data = await res.json(); + assert.deepStrictEqual(data, [{ name: 'Ada' }]); + + globalThis.fetch = originalFetch; +}); + test('uses Deno env when process env missing', async () => { const originalKey = process.env.GOOGLE_API_KEY; delete process.env.GOOGLE_API_KEY;