Skip to content

Commit

Permalink
docs: update service-worker example (#10617)
Browse files Browse the repository at this point in the history
- be type-safe when in ts (match may return undefined, and indeed if a fetch happens too soon after installation the cache may not be populated yet)
- handle offline case better, including a weird response edge case
  • Loading branch information
quentin-fox authored Dec 13, 2023
1 parent 5b1d1ab commit d67425c
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions documentation/docs/30-advanced/40-service-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,21 +66,39 @@ self.addEventListener('fetch', (event) => {

// `build`/`files` can always be served from the cache
if (ASSETS.includes(url.pathname)) {
return cache.match(url.pathname);
const response = await cache.match(url.pathname);

if (response) {
return response;
}
}

// for everything else, try the network first, but
// fall back to the cache if we're offline
try {
const response = await fetch(event.request);

// if we're offline, fetch can return a value that is not a Response
// instead of throwing - and we can't pass this non-Response to respondWith
if (!(response instanceof Response)) {
throw new Error('invalid response from fetch');
}

if (response.status === 200) {
cache.put(event.request, response.clone());
}

return response;
} catch {
return cache.match(event.request);
} catch (err) {
const response = await cache.match(event.request);

if (response) {
return response;
}

// if there's no cache, then just error out
// as there is nothing we can do to respond to this request
throw err;
}
}

Expand Down

0 comments on commit d67425c

Please sign in to comment.