Cloudflare DevelopersCD
Cloudflare Developers3y ago
7 replies
Matthew

I m having a problem with my KV Cache I

I'm having a problem with my KV Cache. I get this error "this.kv.get is not a function" and I can't figure out why. Here is my implementation
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)

I checked my NAMESPACE and when I console(this.kv) it matches what I setup in Cloudflare.
Was this page helpful?