Cache API

A Cache API permite controlar a leitura e escrita no Edge Cache através das Edge Functions.

Headers da requisição

HeadersDescrição
x-storage-operationoperações de cache-storage (open, has, delete)
x-cache-operationoperações de cache (match, put, delete, none, all)
x-storage-namenome do cache-storage (opcional, padrão: "my-cache")
export async function fetch(request, env, ctx) {
const responseHeaders = { "content-type": "text/plain" };
try {
const cacheName =
request.headers.get("x-cache-name") // prioridade ao header
?? env.CACHE_NAME // fallback para binding
?? "default"; // fallback final
const cache = await caches.open(cacheName);
if (request.headers.get("x-clear-cache")) {
await cache.delete(request);
return new Response(null, { headers: responseHeaders, status: 205 });
}
const cachedResponse = await cache.match(request);
if (cachedResponse) return cachedResponse;
const originURL = "https://o72cj3e0vu.map.azionedge.net";
const fetchResponse = await fetch(originURL);
ctx.waitUntil(cache.put(request, fetchResponse.clone()));
return new Response(
"I couldn't load cache, because I'm a teapot!",
{ headers: responseHeaders, status: 418 }
);
} catch (err) {
console.error(err);
return new Response(err.message, { headers: responseHeaders, status: 500 });
}
}