-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsw.js
399 lines (363 loc) · 11.2 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
self.addEventListener("install", (event) => {
console.log("[service worker] installed");
self.skipWaiting();
});
const lastEditedRequest = new Request("/api/lastEdited", {
credentials: "include",
});
const booksRequest = new Request("/api/books", {
credentials: "include",
});
async function lastEditedFromCache() {
const cache = await caches.open("v1");
const lastEditedResponse = await cache.match(lastEditedRequest);
if (lastEditedResponse) {
const data = await lastEditedResponse.json();
if (data && data.lastEdited) {
return data.lastEdited;
}
}
return null;
}
async function fetchBooksFromServer() {
const booksResponse = await fetch(booksRequest);
const books = await booksResponse.json();
console.log("books from server", books);
const cache = await caches.open("v1");
cache.put(booksRequest, new Response(JSON.stringify({ books: books.books })));
setLastEditedInCache(books.lastEdited);
return new Response(
JSON.stringify({
books: books.books,
lastEdited: books.lastEdited,
serviceWorkerRunning: true,
})
);
}
async function setLastEditedInCache(lastEdited) {
const cache = await caches.open("v1");
cache.put(lastEditedRequest, new Response(JSON.stringify({ lastEdited })));
console.log("set last edited in cache to:", lastEdited);
}
async function lastEditedFromServer() {
const result = await fetch(lastEditedRequest);
if (!result.ok) return null;
const data = await result.json();
if (!data || !data.lastEdited) return null;
return data.lastEdited;
}
async function fetchBooksFromCache() {
const cache = await caches.open("v1");
const cachedBookData = await cache.match(booksRequest);
if (!cachedBookData) {
console.warn("no cachedBookData");
return false;
}
const data = await cachedBookData.json();
if (!data || !data.books) {
console.warn("no data or books");
return false;
}
return data.books;
}
async function updateCacheWithChapter(books, data) {
const { chapter } = data;
const book = books.find((book) => book.bookid === chapter.bookid);
if (!book) {
console.warn("book not found", books, chapter);
return false;
}
const chapterIndex = book.chapters.findIndex(
(c) => c.chapterid === chapter.chapterid
);
if (chapterIndex === -1) {
console.warn("chapter not found. Must be a move", chapter);
// first remove the chapter from the old book
books.forEach((_book) => {
_book.chapters = _book.chapters.filter(
(c) => c.chapterid !== chapter.chapterid
);
_book.chapterOrder = _book.chapterOrder.filter(
(c) => c !== chapter.chapterid
);
});
// then add to new book
book.chapters.push(chapter);
// book.chapterOrder.push(chapter.chapterid);
} else {
book.chapters[chapterIndex] = chapter;
}
return books;
}
async function updateCacheWithBook(books, data) {
const { book } = data;
const bookIndex = books.findIndex((b) => b.bookid === book.bookid);
if (bookIndex === -1) {
console.warn("book not found", books, book);
return false;
}
const bookChapters = books[bookIndex].chapters;
book.chapters = bookChapters;
books[bookIndex] = book;
return books;
}
function deepEqual(obj1, obj2) {
if (obj1 === obj2) {
return true;
} else if (isObject(obj1) && isObject(obj2)) {
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
console.log(
"keys not equal length",
Object.keys(obj1).length,
Object.keys(obj2).length
);
return false;
}
for (var prop in obj1) {
if (!deepEqual(obj1[prop], obj2[prop])) {
console.log("not equal", prop, obj1[prop], obj2[prop]);
return false;
}
}
return true;
} else if (Array.isArray(obj1) && Array.isArray(obj2)) {
if (obj1.length !== obj2.length) {
console.log("not equal length", obj1.length, obj2.length);
return false;
}
for (var i = 0; i < obj1.length; i++) {
if (!deepEqual(obj1[i], obj2[i])) {
console.log("not equal", obj1[i], obj2[i]);
return false;
}
}
return true;
}
return false;
// Private
function isObject(obj) {
if (typeof obj === "object" && obj != null) {
return true;
} else {
return false;
}
}
}
function prettyDate(date) {
const d = new Date(date);
return d.toLocaleString();
}
async function getBooksFromCacheOrServer() {
const cachedBooks = await fetchBooksFromCache();
if (!cachedBooks) {
console.warn("no books in cache, fetching from server");
return fetchBooksFromServer();
}
const cachedLastEdited = await lastEditedFromCache();
if (!cachedLastEdited) {
console.warn("no last edited in cache, fetching from server");
return fetchBooksFromServer();
}
const freshLastEdited = await lastEditedFromServer();
console.log(
"cached last edited",
cachedLastEdited,
prettyDate(cachedLastEdited)
);
console.log(
"fresh last edited",
freshLastEdited,
prettyDate(freshLastEdited)
);
if (!freshLastEdited) {
console.warn("no last edited from server, fetching from server");
return fetchBooksFromServer();
}
const compare = false;
if (compare) {
const res1 = await fetchBooksFromServer();
const clone = res1.clone();
const json = await res1.json();
const server = json.books;
const cache = await fetchBooksFromCache();
console.log("server", server);
console.log("cache", cache);
const equal = deepEqual(server, cache);
console.log("deep equal", equal);
return new Response(
JSON.stringify({
books: server,
lastEdited: json.lastEdited,
deepEqual: equal,
serviceWorkerRunning: true,
})
);
} else if (cachedLastEdited < freshLastEdited) {
console.warn("local copy is outdated, fetching from server");
const cache = await caches.open("v1");
// first, back up the cache data
cache.put(
"/api/books/backup",
new Response(JSON.stringify({ books: cachedBooks }))
);
return fetchBooksFromServer();
} else {
console.warn("fetching local copy from cache!");
const books = await fetchBooksFromCache();
const lastEdited = await lastEditedFromCache();
return new Response(
JSON.stringify({
books,
lastEdited,
serviceWorkerRunning: true,
fromCache: true,
})
);
}
}
async function saveChapter(request) {
return await saveBase("saveChapter", request, updateCacheWithChapter);
}
async function saveBook(request) {
return await saveBase("saveBook", request, updateCacheWithBook);
}
async function newChapter(request) {
return await saveBase("newChapter", request, (books, reqData, chapter) => {
const { bookid } = reqData;
const book = books.find((b) => b.bookid === bookid);
if (!book) {
console.warn("book not found for newChapter", bookid);
return false;
}
book.chapters.push(chapter);
book.chapterOrder.push(chapter.chapterid);
return books;
});
}
async function newBook(request) {
return await saveBase("newBook", request, (books, _, book) => {
books.push(book);
return books;
});
}
async function deleteChapter(request) {
return await saveBase("deleteChapter", request, (books, reqData, _) => {
const { chapterid, bookid } = reqData;
const book = books.find((b) => b.bookid === bookid);
if (!book) {
console.warn("book not found for deleteChapter", bookid, chapterid);
return false;
}
book.chapters = book.chapters.filter((c) => c.chapterid !== chapterid);
book.chapterOrder = book.chapterOrder.filter((c) => c !== chapterid);
return books;
});
}
async function deleteBook(request) {
return await saveBase("deleteBook", request, (books, reqData, _) => {
return books.filter((b) => b.bookid !== reqData.bookid);
});
}
async function saveBase(type, request, updateFunc) {
const requestClone = request.clone();
const response = await fetch(request);
const responseClone = response.clone();
if (responseClone.ok) {
const booksFromCache = await fetchBooksFromCache();
if (booksFromCache) {
const requestData = await requestClone.json();
const responseData = await responseClone.json();
const updatedBooks = await updateFunc(
booksFromCache,
requestData,
responseData
);
if (updatedBooks) {
const cache = await caches.open("v1");
cache.put(
booksRequest,
new Response(JSON.stringify({ books: updatedBooks }))
);
setLastEditedInCache(responseData.lastHeardFromServer);
console.log("updated cache", type);
} else {
console.log("something went wrong updating the cache");
}
} else {
console.log("no books in cache, can't update", type);
}
} else {
console.log("failed to update on server", type);
}
return response;
}
function clearCache() {
console.log("clearing cache");
caches.keys().then(function (names) {
for (let name of names) caches.delete(name);
});
localStorage.clear();
}
async function serveFromCache(request) {
console.log("serveFromCache", request.url);
// Try to get the response from a cache.
const cachedResponse = await caches.match(request);
// Return it if we found one.
if (cachedResponse) return cachedResponse;
// If we didn't find a match in the cache, use the network.
console.log("serveFromCache: not found in cache", request.url);
const response = await fetch(request);
const cache = await caches.open("v1");
const clone = response.clone();
cache.put(request, clone);
return response;
}
self.addEventListener("fetch", async (event) => {
//console.warn("[service worker] fetch", event.request.url);
//console.log(event.request);
if (event.request.url.endsWith("/api/books")) {
event.respondWith(getBooksFromCacheOrServer());
} else if (
event.request.method === "PUT" &&
event.request.url.endsWith("/api/chapter")
) {
console.log("save chapter", event.request);
event.respondWith(saveChapter(event.request));
} else if (
event.request.method === "PUT" &&
event.request.url.endsWith("/api/book")
) {
console.log("save book", event.request);
event.respondWith(saveBook(event.request));
} else if (
event.request.method === "POST" &&
event.request.url.endsWith("/api/chapter")
) {
console.log("new chapter", event.request);
event.respondWith(newChapter(event.request));
} else if (
event.request.method === "POST" &&
event.request.url.endsWith("/api/book")
) {
console.log("new book", event.request);
event.respondWith(newBook(event.request));
} else if (
event.request.method === "DELETE" &&
event.request.url.contains("/api/chapter")
) {
console.log("delete chapter", event.request);
event.respondWith(deleteChapter(event.request));
} else if (
event.request.method === "DELETE" &&
event.request.url.contains("/api/book")
) {
console.log("delete book", event.request);
event.respondWith(deleteBook(event.request));
} else if (event.request.url.endsWith("/logout")) {
clearCache();
} else if (event.request.url.includes("/css")) {
event.respondWith(serveFromCache(event.request));
} else if (event.request.url.includes("/images")) {
event.respondWith(serveFromCache(event.request));
}
});