-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
154 lines (132 loc) · 4.05 KB
/
sw.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
const cacheName = 'latestNews-v1';
const offlineUrl = 'offline-page.html';
self.addEventListener('install', event => {
// TODO Arbeitsauftrag
self.skipWaiting();
event.waitUntil(
caches.open(cacheName)
.then(cache => cache.addAll([
'./js/main.js',
'./images/newspaper.svg',
'./css/site.css',
'./header.html',
'./footer.html',
'offline-page.html'
]))
);
});
self.addEventListener('activate', function (event) {
// TODO Arbeitsauftrag
self.clients.claim();
});
function timeout(delay) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(new Response('', {
status: 408,
statusText: 'Request timed out.'
}));
}, delay);
});
}
function resolveFirstPromise(promises) {
return new Promise((resolve, reject) => {
promises = promises.map(p => Promise.resolve(p));
promises.forEach(p => p.then(resolve));
promises.reduce((a, b) => a.catch(() => b))
.catch(() => reject(Error("All failed")));
});
};
function streamArticle(url) {
try {
new ReadableStream({});
}
catch (e) {
return new Response("Streams not supported");
}
const stream = new ReadableStream({
start(controller) {
const startFetch = caches.match('header.html');
const bodyData = fetch(`data/${url}.html`)
.catch(() => new Response('Body fetch failed'));
const endFetch = caches.match('footer.html');
function pushStream(stream) {
const reader = stream.getReader();
function read() {
return reader.read().then(result => {
if (result.done) return;
controller.enqueue(result.value);
return read();
});
}
return read();
}
startFetch
.then(response => pushStream(response.body))
.then(() => bodyData)
.then(response => pushStream(response.body))
.then(() => endFetch)
.then(response => pushStream(response.body))
.then(() => controller.close());
}
});
return new Response(stream, {
headers: { 'Content-Type': 'text/html' }
})
}
function getQueryString(field, url = window.location.href) {
const reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
const result = reg.exec(url);
return result ? result[1] : null;
};
self.addEventListener('fetch', function (event) {
const url = new URL(event.request.url);
if (url.pathname.endsWith('/article.html')) {
// TODO Arbeitsauftrag
const articleId = getQueryString('id');
const articleUrl = `data-${articleId}`;
event.respondWith(streamArticle(articleUrl));
} else if (url.pathname.endsWith('/index.html')) {
const indexUrl = 'data-index';
// Respond with a stream
event.respondWith(streamArticle(indexUrl));
} else if (/googleapis/.test(event.request.url)) {
// Check for the googleapis domain
event.respondWith(
resolveFirstPromise([
timeout(500),
fetch(event.request)
])
);
} else {
// Else process all other requests as expected
event.respondWith(
caches.match(event.request)
.then(function (response) {
if (response) {
return response;
}
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function (response) {
if (!response || response.status !== 200) {
return response;
}
var responseToCache = response.clone();
caches.open(cacheName)
.then(function (cache) {
cache.put(event.request, responseToCache);
});
return response;
}
).catch(error => {
// Check if the user is offline first and is trying to navigate to a web page
if (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html')) {
// Return the offline page
return caches.match(offlineUrl);
}
});
})
);
}
});