@workkit/kv
v0.2.1
Published
Typed KV operations with Standard Schema validation for Cloudflare Workers
Maintainers
Readme
@workkit/kv
Typed KV client with automatic serialization, batching, and key prefixing
Install
bun add @workkit/kvUsage
Before (raw KV API)
// Manual JSON serialization, no type safety, verbose error handling
const raw = await env.USERS_KV.get("user:alice", "json")
const user = raw as User | null // cast and pray
await env.USERS_KV.put("user:alice", JSON.stringify({ name: "Alice" }), {
expirationTtl: 3600,
})
// Listing requires manual cursor management
let cursor: string | undefined
const keys: string[] = []
do {
const result = await env.USERS_KV.list({ cursor })
keys.push(...result.keys.map((k) => k.name))
cursor = result.list_complete ? undefined : result.cursor
} while (cursor)After (workkit kv)
import { kv } from "@workkit/kv"
const users = kv<User>(env.USERS_KV, { prefix: "user:", defaultTtl: 3600 })
await users.put("alice", { name: "Alice", role: "admin" }) // auto-serialized, auto-prefixed
const user = await users.get("alice") // User | null — typed
// Batch operations
await users.batchPut([
{ key: "bob", value: { name: "Bob", role: "user" } },
{ key: "carol", value: { name: "Carol", role: "admin" } },
])
// Auto-paginated listing
for await (const entry of users.list()) {
console.log(entry.name) // auto-paginated, prefix stripped
}API
kv<T>(binding, options?)
Create a typed KV client.
Options:
prefix— Key prefix applied to all operationsdefaultTtl— Default TTL in seconds forput()defaultCacheTtl— Default cache TTL forget()serializer—"json"(default) or"text"
Methods:
get(key, opts?)— Get a value (T | null)getWithMetadata(key, opts?)— Get value + metadataput(key, value, opts?)— Store a valuedelete(key)— Delete a keylist(opts?)— Auto-paginated async iteratorbatchGet(keys)— Get multiple keysbatchPut(entries)— Put multiple key-value pairsbatchDelete(keys)— Delete multiple keys
Utilities
validateKey(key)— Validate a KV keyprefixKey(prefix, key)/stripPrefix(prefix, key)— Key manipulation
License
MIT
