Skip to content

Instantly share code, notes, and snippets.

@mhart
Created August 8, 2024 02:24
Show Gist options
  • Save mhart/eee0779f12915087c9439cddc9bed119 to your computer and use it in GitHub Desktop.
Save mhart/eee0779f12915087c9439cddc9bed119 to your computer and use it in GitHub Desktop.
  • npx wrangler kv namespace list
  • npx wrangler kv namespace create api-and-kv-example
import { Hono } from 'hono';
const app = new Hono<{ Bindings: Env }>();
app.get('/repos/:username', async (c) => {
const username = c.req.param('username');
const cached = await c.env.KV.get(`repos:${username}`, 'json');
if (cached) {
return c.json(cached);
} else {
const resp = await fetch(`https://api.github.com/users/${username}/repos`, {
headers: {
'User-Agent': 'CF Workers Demo',
},
});
const data = await resp.json();
await c.env.KV.put(`repos:${username}`, JSON.stringify(data), {
expirationTtl: 60,
});
return c.json(data as any);
}
});
export default app;
#:schema node_modules/wrangler/config-schema.json
name = "api-and-kv-example"
main = "src/index.ts"
compatibility_date = "2024-08-06"
[[kv_namespaces]]
binding = "KV"
id = "d54e4637ca4649cc923b6d53c1108229"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment