Skip to content

Commit 0b7a20e

Browse files
authored
Merge pull request #3 from pvdthings/add-service-worker
Catalog: Add service worker to web app
2 parents 8730730 + a1f67d6 commit 0b7a20e

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

apps/web/src/service-worker.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/// <reference types="@sveltejs/kit" />
2+
import { build, files, version } from '$service-worker';
3+
4+
// Create a unique cache name for this deployment
5+
const CACHE = `cache-${version}`;
6+
7+
const ASSETS = [
8+
...build, // the app itself
9+
...files // everything in `static`
10+
];
11+
12+
self.addEventListener('install', (event) => {
13+
// Create a new cache and add all files to it
14+
async function addFilesToCache() {
15+
const cache = await caches.open(CACHE);
16+
await cache.addAll(ASSETS);
17+
}
18+
19+
event.waitUntil(addFilesToCache());
20+
});
21+
22+
self.addEventListener('activate', (event) => {
23+
// Remove previous cached data from disk
24+
async function deleteOldCaches() {
25+
for (const key of await caches.keys()) {
26+
if (key !== CACHE) await caches.delete(key);
27+
}
28+
}
29+
30+
event.waitUntil(deleteOldCaches());
31+
});
32+
33+
self.addEventListener('fetch', (event) => {
34+
// ignore POST requests etc
35+
if (event.request.method !== 'GET') return;
36+
37+
async function respond() {
38+
const url = new URL(event.request.url);
39+
const cache = await caches.open(CACHE);
40+
41+
// `build`/`files` can always be served from the cache
42+
if (ASSETS.includes(url.pathname)) {
43+
const response = await cache.match(url.pathname);
44+
45+
if (response) {
46+
return response;
47+
}
48+
}
49+
50+
// for everything else, try the network first, but
51+
// fall back to the cache if we're offline
52+
try {
53+
const response = await fetch(event.request);
54+
55+
// if we're offline, fetch can return a value that is not a Response
56+
// instead of throwing - and we can't pass this non-Response to respondWith
57+
if (!(response instanceof Response)) {
58+
throw new Error('invalid response from fetch');
59+
}
60+
61+
if (response.ok) {
62+
cache.put(event.request, response.clone());
63+
}
64+
65+
return response;
66+
} catch (err) {
67+
const response = await cache.match(event.request);
68+
69+
if (response) {
70+
return response;
71+
}
72+
73+
// if there's no cache, then just error out
74+
// as there is nothing we can do to respond to this request
75+
throw err;
76+
}
77+
}
78+
79+
event.respondWith(respond());
80+
});

0 commit comments

Comments
 (0)