generated from kittsville/webapp-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.js
88 lines (71 loc) · 2.35 KB
/
worker.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const tools = [
"",
"alphabetizer",
"case-converter",
"generic-formatter",
"json-formatter",
"shared",
"stack-extractor",
"trimmer",
"url-cleaner",
];
const files = [
"/",
"/styles.css",
"/script.js",
];
const cacheName = 'web-tools-v1';
function listCacheables(domain)
{
return tools.map(tool => files.map(file => `${domain}/${tool}${file}`)).flatten();
}
self.addEventListener('install', e =>
{
console.log('Worker install');
e.waitUntil(
listCacheables(self.registration.scope).forEach(url => {
console.log('Caching file ' + url);
fetch(url, {cache: "no-cache"}).then(r => cacheResponse(url, r));
})
);
});
self.addEventListener('activate', e => {
console.log('Worker activate');
e.waitUntil(
caches.keys().then(names => names.forEach(
name => (name !== cacheName) && caches.delete(name)
))
);
return self.clients.claim();
});
self.addEventListener('fetch', e =>
{
const url = e.request.url;
e.respondWith(
caches.open(cacheName)
.then(cache => cache.match(e.request))
.then(cached =>
{
console.log(cached ? 'Cache Available' : 'Not Cached', url);
if (! (cached instanceof Response))
{
console.log('Long-Fetching', url);
return fetch(e.request, {cache: "no-cache"}).then(rsp => cacheResponse(e.request, rsp))
}
console.log('Short-Fetching', url);
return timed_fetch(e.request, 1500)
.then(rsp => {console.log('Fetched and cached', url); return rsp;})
.then(rsp => cacheResponse(e.request, rsp))
// If the underlying fetch call errors or doesn't return in 1500ms, return the cached version
.catch(() => {console.log('Short fetch failed, falling back to cache', url); return cached;})
}
))
});
const cacheResponse = (req, rsp) => caches.open(cacheName)
.then(cache => cache.put(req, rsp.clone()))
.then(() => rsp);
const timed_fetch = (url, timeout) => with_timeout(fetch(url, {mode: 'cors', credentials: 'omit', cache: "no-cache"}), timeout);
const with_timeout = (promise, ms) => new Promise((accept, reject) => {
setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
promise.then(accept, reject);
});