From 376f4afae8e20898b3c2af95a16e7bfc4fa925ba Mon Sep 17 00:00:00 2001 From: Adishwar Rishi Date: Fri, 1 Dec 2023 02:26:51 +0530 Subject: [PATCH] docs: Add a section to the readme for the Cloudflare KV adapter (#79) * (docs): Add a section to the readme for the Cloudflare KV adapter * Remove extra comments in CF workers code example - the reasoning should be self explanatory --- README.md | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/README.md b/README.md index 31ae963..def7883 100644 --- a/README.md +++ b/README.md @@ -292,6 +292,59 @@ const data = await cachified({ }); ``` +### Adapter for [Cloudflare KV](https://developers.cloudflare.com/kv/) + +For additional information or to report issues, please visit the [cachified-adapter-cloudflare-kv repository](https://github.com/AdiRishi/cachified-adapter-cloudflare-kv). + +```ts +import { cachified, Cache } from '@epic-web/cachified'; +import { cloudflareKvCacheAdapter } from 'cachified-adapter-cloudflare-kv'; + +export interface Env { + KV: KVNamespace; + CACHIFIED_KV_CACHE: Cache; +} + +export async function getUserById( + userId: number, + env: Env, +): Promise> { + return cachified({ + key: `user-${userId}`, + cache: env.CACHIFIED_KV_CACHE, + async getFreshValue() { + const response = await fetch( + `https://jsonplaceholder.typicode.com/users/${userId}`, + ); + return response.json(); + }, + ttl: 60_000, // 1 minute + staleWhileRevalidate: 300_000, // 5 minutes + }); +} + +export default { + async fetch( + request: Request, + env: Env, + ctx: ExecutionContext, + ): Promise { + env.CACHIFIED_KV_CACHE = cloudflareKvCacheAdapter({ + kv: env.KV, + keyPrefix: 'mycache', // optional + name: 'CloudflareKV', // optional + }); + const userId = Math.floor(Math.random() * 10) + 1; + const user = await getUserById(userId, env); + return new Response(JSON.stringify(user), { + headers: { + 'Content-Type': 'application/json', + }, + }); + }, +}; +``` + ## Advanced Usage ### Stale while revalidate