Skip to content

Commit

Permalink
docs: Add a section to the readme for the Cloudflare KV adapter (#79)
Browse files Browse the repository at this point in the history
* (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
  • Loading branch information
AdiRishi authored Nov 30, 2023
1 parent 4a84a8d commit 376f4af
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<string, unknown>> {
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<Response> {
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
Expand Down

0 comments on commit 376f4af

Please sign in to comment.