Skip to content

Update SimpleCache examples #1080

Open
Open
@nnlugovoy

Description

@nnlugovoy

Improve SimpleCache API examples for getOrSet

Current docs state that SimpleCache.getOrSet() returns a SimpleCacheEntry, which is not accurate.
In fact, it returns Promise that resolves to SimpleCacheEntry

Then, example should look like this, with proper await calls

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 = await SimpleCache.getOrSet(path, async () => {
    return {
      value: await render(path),
      // Store the page in the cache for 1 minute.
      ttl: 60
    }
  });
  if (null === page) {
    return new Response(null, { status: 404 });
  } else {
    let content = await page.text();
    return new Response(content, {
      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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions