import { kvResponseCache } from "./caches"; import type { Filter } from "./types"; import type { Context, Env, MiddlewareHandler } from "hono"; type Namespace = string | ((c: Context) => string); interface GetCacheKey { (c: Context): string; } type KVCacheOption }> = { key: keyof E["Bindings"]; namespace: Namespace; getCacheKey?: GetCacheKey; options?: KVNamespacePutOptions; }; export const defaultGetCacheKey = (c: Context) => c.req.url; export const kvCaches = }>({ key: bindingKey, namespace, options, getCacheKey = defaultGetCacheKey, }: KVCacheOption): MiddlewareHandler => async (c, next) => { const kv: KVNamespace = c.env?.[bindingKey] as KVNamespace; const kvNamespace = typeof namespace === "function" ? namespace(c) : namespace; const kvCaches = kvResponseCache(kv); const cache = kvCaches(kvNamespace); const key = getCacheKey(c); const response = await cache.match(key); if (response) { response.headers.set("X-KV-CACHE", "hit"); return response; } await next(); if (c.res.status >= 200 && c.res.status < 300) { c.executionCtx.waitUntil(cache.put(key, c.res.clone(), options)); } };