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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 12 additions & 8 deletions netlify/edge-functions/opensheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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;
}
Expand Down
15 changes: 15 additions & 0 deletions test/opensheet.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading