Skip to main content
Version: 3.28.0

SimpleCache.getOrSet

The getOrSet() method attempts to get an entry from the cache for the supplied key. If no entry is found (or has expired), the supplied set function is executed and its result is inserted into the cache under the supplied key and for the supplied ttl (Time-To-Live) duration, provided in seconds.

Syntax

getOrSet(key, set)
getOrSet(key, set, length)

Parameters

  • key : string
    • The key to lookup and/or store the supplied entry under within the cache.
  • set : Function
    • The function to execute if and only if the cache does not have a usable entry for the supplied key. The function should return a Promise which resolves with the following interface:
      • value : ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal
        • The value to store within the cache.
      • ttl : number
        • The maximum number of seconds to store the supplied entry in the cache.
      • length : number optional
        • The length of the value being stored within the cache. This is only used when the value is a ReadableStream.

Return value

Returns a SimpleCacheEntry.

Exceptions

  • If the provided key:
    • Cannot be coerced to a string
    • Is an empty string
    • Is longer than 8135 characters
  • If the provided ttl:
    • Cannot be coerced to a number
    • Is a negative number
    • Is NaN
    • Is Inifinity

Examples

In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning.

/// <reference types="@fastly/js-compute" />

import { SimpleCache } from 'fastly:cache';

addEventListener('fetch', event => event.respondWith(app(event)));

async function app(event) {
const path = new URL(event.request.url).pathname;
let page = SimpleCache.getOrSet(path, async () => {
return {
value: await render(path),
// Store the page in the cache for 1 minute.
ttl: 60
}
});
return new Response(page, {
headers: {
'content-type': 'text/plain;charset=UTF-8'
}
});
}

async function render(path) {
// expensive/slow function which constructs and returns the contents for a given path
await new Promise(resolve => setTimeout(resolve, 10_000));
return path;
}