import type { KVNamespace } from '@cloudflare/workers-types'
export type KVCacheInstanceType<T> = InstanceType<typeof KVCache<T>>
export class KVCache<T> {
private kv: KVNamespace
constructor(namespace: KVNamespace) {
this.kv = namespace
}
async get(key: string): Promise<T | null> {
try {
const value = await this.kv.get(key, 'text')
return value ? this.parseJson(value) : null
} catch (error) {
console.log(error)
return null
}
}
async set(key: string, value: T, ttl?: number): Promise<void> {
try {
const stringValue = this.stringifyJson(value)
const options = ttl ? { expirationTtl: ttl } : undefined
await this.kv.put(key, stringValue, options)
} catch (error) {
console.log(error)
return
}
}
async delete(key: string) {
...
}
private parseJson(value: string): T | null {
...
}
private stringifyJson(value: T): string {
...
}
}
// Usage
const cache = new KVCache<GooglePublicKeys>(config.namespace)
import type { KVNamespace } from '@cloudflare/workers-types'
export type KVCacheInstanceType<T> = InstanceType<typeof KVCache<T>>
export class KVCache<T> {
private kv: KVNamespace
constructor(namespace: KVNamespace) {
this.kv = namespace
}
async get(key: string): Promise<T | null> {
try {
const value = await this.kv.get(key, 'text')
return value ? this.parseJson(value) : null
} catch (error) {
console.log(error)
return null
}
}
async set(key: string, value: T, ttl?: number): Promise<void> {
try {
const stringValue = this.stringifyJson(value)
const options = ttl ? { expirationTtl: ttl } : undefined
await this.kv.put(key, stringValue, options)
} catch (error) {
console.log(error)
return
}
}
async delete(key: string) {
...
}
private parseJson(value: string): T | null {
...
}
private stringifyJson(value: T): string {
...
}
}
// Usage
const cache = new KVCache<GooglePublicKeys>(config.namespace)