-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserviceworker.js
333 lines (296 loc) · 10.4 KB
/
serviceworker.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
//-----------------------------------------------------------------------------
//
// ### PWA Bunga! Service Worker
//
// Documentation of serviceworker.js
// ---------------------------------
// https://pwabunga.com/documentation/pwa/serviceworker.html
//
//-----------------------------------------------------------------------------
//--------------------------------------------------------------------
//
// ### Cache & Request Processing Strategy
//
//--------------------------------------------------------------------
// # Cache Config
//---------------
// -- Cache name and version
const cacheTitle = 'yourAppName'
const cacheVersion = 'v1.0'
const cacheName = cacheTitle + '-' + cacheVersion
// -- static assets
const contentToCache = [
// - Pages
'/',
'index.html',
// - Favicons
'favicon.ico',
'favicon-16.png',
'favicon-32.png',
// - CSS
'assets/css/pwabunga.css',
'assets/css/styles.css',
// - JS
'assets/js/scripts.js',
// - PWA
'pwa/css/pwabunga-ui.css',
'pwa/icons/apple-touch-icon.png',
'pwa/icons/icon-192.png',
'pwa/icons/icon-512.png',
'pwa/icons/icon-maskable-192.png',
'pwa/icons/icon-maskable-512.png',
'pwa/js/pwabunga.js',
'pwa/app.webmanifest'
]
// # Request Processing Strategy Config
//-------------------------------------
// -- Request Processing Strategy
const requestProcessingMethod = 'cacheFirst'
// -- Dynamic folder (Network Only Request Processing)
const dynamicFolder = '/api/'
//--------------------------------------------------------------------
// ## Add to cache
//--------------------------------------------------------------------
// # Add Resources to cache
//-------------------------
const addResourcesToCache = async (resources) => {
// -- Open the cache with the specified name (cacheName)
const cache = await caches.open(cacheName)
// -- Add all resources in the resources array to the cache
await cache.addAll(resources)
}
// # Put request to cache
//-----------------------
const putInCache = async (request, response) => {
// -- Open the cache with the specified name (cacheName)
const cache = await caches.open(cacheName)
// -- Add the response to the cache for the given request
await cache.put(request, response)
}
//--------------------------------------------------------------------
// ## Delete cache
//--------------------------------------------------------------------
// # Delete cache
//---------------
const deleteCache = async (key) => {
// -- Delete the cache with the specified key
await caches.delete(key)
}
// # Delete old caches
//--------------------
const deleteOldCaches = async () => {
// -- Define the cache to keep
const cacheKeepList = [cacheName]
// -- Get a list of all cache keys
const keyList = await caches.keys()
// -- Filter the list of keys to caches that are not in the keep list
const cachesToDelete = keyList.filter((key) => !cacheKeepList.includes(key))
// -- Delete all caches to be deleted
await Promise.all(cachesToDelete.map(deleteCache))
}
//--------------------------------------------------------------------
// ## Request Processing method
//--------------------------------------------------------------------
// # Cache Only
//-------------
const cacheOnly = async ({ request }) => {
// -- Try to match the request with a cached response
const responseFromCache = await caches.match(request)
// -- If a cached response is found
if (responseFromCache) {
// - Return the response from cache
return responseFromCache
} else {
// - If no cached response is found
return new Response("No cached response found", {
// Return a 404 response with a plain text error message
status: 404,
headers: { "Content-Type": "text/plain" }
})
}
}
// # Network Only
//---------------
const networkOnly = async ({ request }) => {
try {
// -- Try to fetch the request from the network
const responseFromNetwork = await fetch(request)
// -- If the network request succeeds, return the response
return responseFromNetwork
} catch (error) {
// -- If the network request fails
return new Response("Network error happened", {
// - Return a 408 response with a plain text error message
status: 408,
headers: { "Content-Type": "text/plain" }
})
}
}
// # Cache first method
//---------------------
const cacheFirst = async ({ request }) => {
// -- If the request URL includes the dynamicFolder
if (request.url.includes(dynamicFolder)) {
// - Always fetch it from the network
return fetch(request)
}
// -- Try to match the request with a cached response
const responseFromCache = await caches.match(request)
// -- If a cached response is found
if (responseFromCache) {
// Return it
return responseFromCache
}
// -- If the response is not in cache
try {
// - Try to fetch it from the network
const responseFromNetwork = await fetch(request)
// - Cache the response
putInCache(request, responseFromNetwork.clone())
// - Return the response from network
return responseFromNetwork
} catch (error) {
// - If there is a network error, return an error message
return new Response("Network error happened", {
status: 408,
headers: { "Content-Type": "text/plain" }
})
}
}
// # Network first method
//-----------------------
const networkFirst = async ({ request }) => {
try {
// -- Try to fetch the resource from the network
const responseFromNetwork = await fetch(request)
// -- If the network request is successful, store a copy of the response in cache
putInCache(request, responseFromNetwork.clone())
// -- Return the response from networkr
return responseFromNetwork
} catch (error) {
// -- If there was an error fetching from the network, attempt to retrieve the response from cache
const responseFromCache = await caches.match(request)
// -- If the cached response exists
if (responseFromCache) {
// - Return the response from cache
return responseFromCache
}
// -- If there was no cached response and the network request failed
return new Response("Network error happened", {
// - return a 408 response with a plain text error message
status: 408,
headers: { "Content-Type": "text/plain" }
})
}
}
// # Stale while revalidate method
//--------------------------------
const staleWhileRevalidate = async ({ request }) => {
// -- open cache
const cache = await caches.open(cacheName)
// -- check if response is in cache
const responseFromCache = await caches.match(request)
// -- fetch response from network
const responseFromNetwork = fetch(request)
// -- If a cached response is found
if (responseFromCache) {
// - Clone the cached response to avoid modifying the original
const responseClone = responseFromCache.clone()
// - Asynchronously fetch a fresh response from the network
responseFromNetwork.then(response => {
// Put the fresh response into the cache
cache.put(request, response.clone())
})
// - Return the cached response to the user
return responseClone
}
try {
// - Attempt to fetch the request from the network
const response = await responseFromNetwork
// - If successful, put the response in the cache
cache.put(request, response.clone())
// - Return it
return response
} catch (error) {
// - If an error occurs
return new Response('Network error occurred.', {
// return a 408 response with a plain text error message
status: 408,
statusText: 'Request Timeout',
headers: { 'Content-Type': 'text/plain' }
})
}
}
//--------------------------------------------------------------------
//
// ### Service Worker Events
//
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// ## Service Worker Install
//--------------------------------------------------------------------
// -- The service worker's "install" event listener
self.addEventListener('install', (event) => {
// - Log the installation message
console.log(cacheName + ' Installation')
// - Wait until the resources are added to the cache
event.waitUntil(
addResourcesToCache(contentToCache)
)
})
//--------------------------------------------------------------------
// ## Service Worker Activate
//--------------------------------------------------------------------
// -- The service worker's "activate" event listener
self.addEventListener('activate', (event) => {
// - This event is triggered when the service worker is activated
event.waitUntil(
// Wait until the deleteOldCaches function has finished running
deleteOldCaches()
)
})
//--------------------------------------------------------------------
// ## Service Worker Message
//--------------------------------------------------------------------
// -- The service worker's "message" event listener
self.addEventListener('message', (event) => {
// - If the message is 'SKIP_WAITING'
if (event.data === 'SKIP_WAITING') {
// Call the skipWaiting method to activate the service worker immediately
self.skipWaiting()
}
// - If the message is 'GET_VERSION'
if (event.data === 'GET_VERSION') {
// Send the cache version to all clients associated with the Service Worker
self.clients.matchAll().then(function(clients) {
// For each client
clients.forEach(function(client) {
// Send a message containing the cache version
client.postMessage(cacheVersion)
})
})
}
})
//--------------------------------------------------------------------
// ## Service Worker Responses to requests
//--------------------------------------------------------------------
// -- The service worker's "message" event listener
self.addEventListener('fetch', (event) => {
// - Get the request object from the event
const request = event.request
// - Define a mapping of request processing methods
const methods = {
'cacheOnly': cacheOnly,
'networkOnly': networkOnly,
'cacheFirst': cacheFirst,
'networkFirst': networkFirst,
'staleWhileRevalidate': staleWhileRevalidate
}
// - Get the processing method from the mapping based on the current request processing method
const method = methods[requestProcessingMethod]
// - If a processing method exists for the current request processing method
if (method) {
// Use it to handle the request
event.respondWith(method({request}))
}
})