function uint8ArrayToHex(arr) {
return Array.prototype.map.call(arr, (x) => (('0' + x.toString(16)).slice(-2))).join('');
}
async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
return uint8ArrayToHex(new Uint8Array(hashBuffer));
}
async function fetchContent(event, cacheKey) {
const cache = caches.default;
const response = await fetch(event.request);
response.headers.set('Cache-Control', 's-maxage=10');
event.waitUntil(cache.put(cacheKey, response.clone()));
response.headers.append('x-edgefunctions-cache', 'miss');
return response;
}
async function handleRequest(event) {
const request = event.request;
const body = await request.clone().text();
const hash = await sha256(body);
const cacheKey = `${request.url}${hash}`;
const cache = caches.default;
try {
let response = await cache.match(cacheKey);
if (!response) {
return fetchContent(event, cacheKey);
}
response.headers.append('x-edgefunctions-cache', 'hit');
return response;
} catch (error) {
await cache.delete(cacheKey);
return fetchContent(event, cacheKey);
}
return response;
}
addEventListener('fetch', (event) => {
try {
const request = event.request;
if (request.method.toUpperCase() === 'POST') {
return event.respondWith(handleRequest(event));
}
return event.respondWith(fetch(request));
} catch (e) {
return event.respondWith(new Response('Error thrown ' + e.message));
}
});
Was this page helpful?