Cache functions result in your Edge-first applications.

Constructors

Properties

Accessors

Methods

Constructors

Properties

kv: KVNamespace<string>
prefix: string = "cache"

Accessors

  • get binding(): KVNamespace<string>
  • A read-only property that gives you the KVNamespace used by the Cache object.

    The namespace can be used to access the KVNamespace directly in case you need to integrate with it.

    Returns KVNamespace<string>

    let namespace = cache().binding;
    

Methods

  • The cache().fetch method is used to get a value from the cache or calculate it if it's not there.

    The function expects the key, the TTL, and a function that will be called to calculate the value if it's not in the cache.

    Type Parameters

    • T extends Jsonifiable

    Parameters

    Returns Promise<T>

    let ONE_HOUR_IN_SECONDS = 3600;

    let value = await cache().fetch("key", ONE_HOUR_IN_SECONDS, async () => {
    // do something expensive and return the value
    });

    // The TTL is optional, it defaults to 60 seconds if not provided.
    await cache().fetch("another-key", async () => {
    // The TTL is optional, it defaults to 60 seconds
    });
  • The cache().fetch method is used to get a value from the cache or calculate it if it's not there.

    The function expects the key, the TTL, and a function that will be called to calculate the value if it's not in the cache.

    Type Parameters

    • T extends Jsonifiable

    Parameters

    • key: string

      The cache key to use, always prefixed by cache:

    • ttl: number

      The time-to-live for the cache, in seconds

    • callback: CallbackFunction<T>

      The function to call if the cache is not found

    Returns Promise<T>

    let ONE_HOUR_IN_SECONDS = 3600;

    let value = await cache().fetch("key", ONE_HOUR_IN_SECONDS, async () => {
    // do something expensive and return the value
    });

    // The TTL is optional, it defaults to 60 seconds if not provided.
    await cache().fetch("another-key", async () => {
    // The TTL is optional, it defaults to 60 seconds
    });
  • The cache().purge method is used to remove a key from the cache.

    Parameters

    • key: string

      The cache key to delete, always prefixed by cache:

    Returns Promise<void>

    cache().purge("key");