All files / middleware edge-cache.middleware.ts

100% Statements 9/9
100% Branches 6/6
100% Functions 2/2
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40                                1x   10x 3x       7x 7x 1x       6x     6x 3x            
// Edge Cache Middleware - Serve and store responses via Cloudflare Cache API.
// Mount BEFORE contextMiddleware so cached responses skip all database work.
//
// Only caches GET requests with successful responses (status < 400).
// Gracefully degrades in local dev where the Cache API is unavailable.
 
import type { MiddlewareHandler } from "hono";
import { getEdgeCachedResponse, putEdgeCacheResponse } from "../lib/edge-cache";
 
/**
 * Hono middleware that checks the Cloudflare edge cache before running
 * downstream handlers, and caches successful GET responses for `ttl` seconds.
 *
 * @param ttl - Cache duration in seconds (e.g. 1800 for 30 minutes)
 */
export function edgeCacheMiddleware(ttl: number): MiddlewareHandler {
	return async (c, next) => {
		// Only cache GET requests
		if (c.req.method !== "GET") {
			return next();
		}
 
		// Try to serve from edge cache
		const cached = await getEdgeCachedResponse(c.req.raw);
		if (cached) {
			return cached;
		}
 
		// Cache miss - run downstream handlers
		await next();
 
		// Only cache successful responses
		if (c.res.status < 400) {
			c.executionCtx.waitUntil(
				putEdgeCacheResponse(c.req.raw, c.res.clone(), ttl),
			);
		}
	};
}