|
| 1 | +import type { Context, MiddlewareHandler } from 'hono'; |
| 2 | + |
| 3 | +/** |
| 4 | + * KV Cache Middleware based on `hono/cache` built for Cache API. |
| 5 | + * |
| 6 | + * @param {Object} options - The options for the KV cache middleware. |
| 7 | + * @param {KVNamespace} options.kvNamespace - The KV namespace to use for caching. |
| 8 | + * @param {string} [options.cacheKeyPrefix] - A prefix to add to cache keys. |
| 9 | + * @param {Function} [options.keyGenerator] - A function to generate cache keys. |
| 10 | + * @param {number} [options.ttl=3600] - Time-to-live for cached items in seconds. |
| 11 | + * @returns {MiddlewareHandler} The middleware handler function. |
| 12 | + */ |
| 13 | +export const kvCache = (options: { |
| 14 | + kvNamespace: KVNamespace; |
| 15 | + cacheKeyPrefix?: string; |
| 16 | + keyGenerator?: (c: Context) => Promise<string> | string; |
| 17 | + ttl?: number; // TTL in seconds |
| 18 | +}): MiddlewareHandler => { |
| 19 | + return async function kvCache(c, next) { |
| 20 | + let key = c.req.url; |
| 21 | + if (options.keyGenerator) { |
| 22 | + key = await options.keyGenerator(c); |
| 23 | + } |
| 24 | + |
| 25 | + if (options.cacheKeyPrefix) { |
| 26 | + key = options.cacheKeyPrefix + key; |
| 27 | + } |
| 28 | + |
| 29 | + // Attempt to retrieve the cached response |
| 30 | + const cachedResponseBody = await options.kvNamespace.get( |
| 31 | + key, |
| 32 | + 'arrayBuffer', |
| 33 | + ); |
| 34 | + if (cachedResponseBody) { |
| 35 | + // Retrieve stored headers |
| 36 | + const cachedHeadersJson = await options.kvNamespace.get(key + ':headers'); |
| 37 | + const headers = new Headers(); |
| 38 | + if (cachedHeadersJson) { |
| 39 | + const headersObj = JSON.parse(cachedHeadersJson); |
| 40 | + for (const [k, v] of Object.entries(headersObj)) { |
| 41 | + headers.set(k, v as string); |
| 42 | + } |
| 43 | + } |
| 44 | + return new Response(cachedResponseBody, { headers }); |
| 45 | + } |
| 46 | + |
| 47 | + // Proceed to the next middleware or handler |
| 48 | + await next(); |
| 49 | + |
| 50 | + // Cache the response if it's successful |
| 51 | + if (!c.res.ok) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + // Clone the response to read its body |
| 56 | + const resClone = c.res.clone(); |
| 57 | + const resBody = await resClone.arrayBuffer(); |
| 58 | + |
| 59 | + // Store the response body and headers in KV |
| 60 | + const ttl = options.ttl || 3600; // Default TTL is 1 hour |
| 61 | + await options.kvNamespace.put(key, resBody, { expirationTtl: ttl }); |
| 62 | + |
| 63 | + const headersObj: Record<string, string> = {}; |
| 64 | + for (const [k, v] of resClone.headers.entries()) { |
| 65 | + headersObj[k] = v; |
| 66 | + } |
| 67 | + await options.kvNamespace.put( |
| 68 | + key + ':headers', |
| 69 | + JSON.stringify(headersObj), |
| 70 | + { expirationTtl: ttl }, |
| 71 | + ); |
| 72 | + }; |
| 73 | +}; |
0 commit comments