Skip to content

Commit d67425c

Browse files
authored
docs: update service-worker example (#10617)
- 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
1 parent 5b1d1ab commit d67425c

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

documentation/docs/30-advanced/40-service-workers.md

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,21 +66,39 @@ self.addEventListener('fetch', (event) => {
6666

6767
// `build`/`files` can always be served from the cache
6868
if (ASSETS.includes(url.pathname)) {
69-
return cache.match(url.pathname);
69+
const response = await cache.match(url.pathname);
70+
71+
if (response) {
72+
return response;
73+
}
7074
}
7175

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

81+
// if we're offline, fetch can return a value that is not a Response
82+
// instead of throwing - and we can't pass this non-Response to respondWith
83+
if (!(response instanceof Response)) {
84+
throw new Error('invalid response from fetch');
85+
}
86+
7787
if (response.status === 200) {
7888
cache.put(event.request, response.clone());
7989
}
8090

8191
return response;
82-
} catch {
83-
return cache.match(event.request);
92+
} catch (err) {
93+
const response = await cache.match(event.request);
94+
95+
if (response) {
96+
return response;
97+
}
98+
99+
// if there's no cache, then just error out
100+
// as there is nothing we can do to respond to this request
101+
throw err;
84102
}
85103
}
86104

0 commit comments

Comments
 (0)