-
Notifications
You must be signed in to change notification settings - Fork 65
/
sw.ts
53 lines (45 loc) · 1.43 KB
/
sw.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
/// <reference lib="ESNext" />
/// <reference lib="WebWorker" />
export declare const self: ServiceWorkerGlobalScope;
const CACHE_VERSION = 1;
const MXC_DOWNLOAD_CACHE = `mxc_download_v${CACHE_VERSION}`;
const MXC_DOWNLOAD_REGEX = /^\S+\/_matrix\/media\/r0\/download\/\S+$/;
self.addEventListener("activate", function (event) {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== MXC_DOWNLOAD_CACHE) {
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener("fetch", (event: FetchEvent) => {
const { request } = event;
// Only handle mxc download request.
if (request.method !== "GET" || MXC_DOWNLOAD_REGEX.test(request.url) === false) return;
event.respondWith(
caches.open(MXC_DOWNLOAD_CACHE).then((cache) => {
return cache
.match(request)
.then((cachedResponse) => {
if (cachedResponse) {
return cachedResponse;
}
return fetch(request.clone()).then((fetchedResponse) => {
if (fetchedResponse.ok) {
event.waitUntil(cache.put(request, fetchedResponse.clone()));
}
return fetchedResponse;
});
})
.catch((error) => {
console.error(`Service Worker Error fetching ${request.url}:`, error);
throw error;
});
})
);
});