Last active
February 4, 2025 16:14
-
-
Save knowler/bf40d5bc90ee25c5c7fafd94ddae6327 to your computer and use it in GitHub Desktop.
Demo using the Web Cache API as an object cache for Deno Deploy KV.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Hono } from "hono"; | |
const kv = await Deno.openKv(); | |
// You could add a version to this if you wanted to bust it (e.g. if a key needed to be deleted). | |
const kvCache = await caches.open("kv-cache"); | |
// Helper for constructing the URL. | |
function kvCacheURL(slug) { | |
return new URL(slug, "http://kv.invalid/pages/"); | |
} | |
// Helper for getting the (maybe cached) page data. | |
async function getPage(slug) { | |
const cacheURL = kvCacheURL(slug); | |
// Check the object cache for data | |
const matched = await kvCache.match(cacheURL); | |
// Cache hit | |
if (matched) return matched.json(); | |
// Cache miss: get the data from the KV store. | |
const { value: page } = await kv.get(["pages", slug]); | |
if (!page) throw `Page not found: ${slug}`; | |
// Store the data as a JSON response | |
await kvCache.put(cacheURL, Response.json(page)); | |
return page; | |
} | |
// Example using object cache in a route. | |
app.get("/:slug", async (c, next) => { | |
const page = await getPage(c.params.slug); | |
// Pass the page data to the renderer (then maybe the HTTP cache will cache this work for further requests). | |
return c.render(page); | |
}); | |
Deno.serve(app.fetch); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment