Key-Value Storage (@microfn/kv)
@microfn/kv
Section titled “@microfn/kv”The @microfn/kv
module allows you to store and retrieve data that persists across function executions. It’s perfect for caching, user preferences, session data, and any state that needs to survive between runs.
Import
Section titled “Import”import kv from "@microfn/kv";
Quick Snippet
Section titled “Quick Snippet”// Write to the key-value storeawait kv.set("my-key", { message: "Hello World" });
// Read from the key-value storeconst value = await kv.get("my-key");
Examples
Section titled “Examples”Here are a few useful things you can do with @microfn/kv
:
1. Cache an API response
Section titled “1. Cache an API response”Avoid hitting external APIs on every request by caching responses for a specific duration.
export async function main({ url }) { const key = `cache:${url}`; const cached = await kv.get<{ data: any; ts: number }>(key).catch(() => null);
// Return cached data if it's less than an hour old if (cached && Date.now() - cached.ts < 3_600_000) { return { ...cached, fromCache: true }; }
// Fetch fresh data and cache it const res = await fetch(url); const data = await res.json(); await kv.set(key, { data, ts: Date.now() });
return { data, fromCache: false };}
2. Implement a simple counter
Section titled “2. Implement a simple counter”Track hits for a specific route or event.
export async function main({ route }) { const key = `hits:${route}`; const currentHits = (await kv.get<number>(key).catch(() => 0)) + 1; await kv.set(key, currentHits); return { route, hits: currentHits };}
3. Store user preferences
Section titled “3. Store user preferences”Save user-specific settings that can be retrieved later.
export async function main({ userId, prefs }) { const key = `user:${userId}:prefs`; await kv.set(key, prefs); const savedPrefs = await kv.get(key); return { success: true, saved: savedPrefs };}