Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update SimpleCache examples #1080

Open
nnlugovoy opened this issue Jan 7, 2025 · 0 comments
Open

Update SimpleCache examples #1080

nnlugovoy opened this issue Jan 7, 2025 · 0 comments

Comments

@nnlugovoy
Copy link

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant