-
Notifications
You must be signed in to change notification settings - Fork 1
/
service-worker.ts
62 lines (59 loc) · 1.9 KB
/
service-worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="WebWorker" />
interface Window extends ServiceWorkerGlobalScope {}
const sw: ServiceWorkerGlobalScope = self as any;
sw.addEventListener("install", (event: ExtendableEvent) => {
event.waitUntil(
caches.open("blaze").then((cache) => {
return cache.addAll(["/"]);
})
);
});
// TODO: I had to use any, the solutions above (references) were ineffective
// (but un the install works).
// must be fixed.
self.addEventListener("fetch", (event: any) => {
event.respondWith(
fetch(event.request)
.then((networkResponse) => {
if (networkResponse.status === 200) {
const currentEtag = networkResponse.headers.get("X-Blaze-Etag");
return caches.open("blaze").then((cache) => {
return cache.match(event.request).then((cachedResponse) => {
const cachedEtag = cachedResponse
? cachedResponse.headers.get("X-Blaze-Etag")
: null;
if (cachedResponse && currentEtag === cachedEtag) {
return cachedResponse;
} else {
return cache
.put(event.request, networkResponse.clone())
.then(() => {
return networkResponse;
});
}
});
});
} else {
return networkResponse;
}
})
.catch(() => {
return caches.open("blaze").then((cache) => {
return cache
.match(event.request)
.then((cachedResponse) => {
if (cachedResponse) {
return cachedResponse;
} else {
return new Response("You are offline");
}
})
.catch(() => {
return new Response("An error occurred");
});
});
})
);
});