Cache POST requests
Cache POST requests using the Cache API.
export default {async fetch(request, env, ctx) {async function sha256(message) {// encode as UTF-8const msgBuffer = await new TextEncoder().encode(message);// hash the messageconst hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);// convert bytes to hex stringreturn [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");}try {if (request.method.toUpperCase() === "POST") {const body = await request.clone().text();// Hash the request body to use it as a part of the cache keyconst hash = await sha256(body);const cacheUrl = new URL(request.url);// Store the URL in cache by prepending the body's hashcacheUrl.pathname = "/posts" + cacheUrl.pathname + hash;// Convert to a GET to be able to cacheconst cacheKey = new Request(cacheUrl.toString(), {headers: request.headers,method: "GET",});const cache = caches.default;// Find the cache key in the cachelet response = await cache.match(cacheKey);// Otherwise, fetch response to POST request from originif (!response) {response = await fetch(request);ctx.waitUntil(cache.put(cacheKey, response.clone()));}return response;}return fetch(request);} catch (e) {return new Response("Error thrown " + e.message);}},};
const handler: ExportedHandler = {async fetch(request, env, ctx) {async function sha256(message) {// encode as UTF-8const msgBuffer = await new TextEncoder().encode(message);// hash the messageconst hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);// convert bytes to hex stringreturn [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");}try {if (request.method.toUpperCase() === "POST") {const body = await request.clone().text();// Hash the request body to use it as a part of the cache keyconst hash = await sha256(body);const cacheUrl = new URL(request.url);// Store the URL in cache by prepending the body's hashcacheUrl.pathname = "/posts" + cacheUrl.pathname + hash;// Convert to a GET to be able to cacheconst cacheKey = new Request(cacheUrl.toString(), {headers: request.headers,method: "GET",});const cache = caches.default;// Find the cache key in the cachelet response = await cache.match(cacheKey);// Otherwise, fetch response to POST request from originif (!response) {response = await fetch(request);ctx.waitUntil(cache.put(cacheKey, response.clone()));}return response;}return fetch(request);} catch (e) {return new Response("Error thrown " + e.message);}},};export default handler;