-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathconfigureServiceWorker.js
89 lines (82 loc) · 2.53 KB
/
configureServiceWorker.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
import { registerRoute } from 'workbox-routing'
import { skipWaiting, clientsClaim } from 'workbox-core'
import { precacheAndRoute } from 'workbox-precaching'
import { CacheFirst } from 'workbox-strategies'
import { ExpirationPlugin } from 'workbox-expiration'
import { CacheableResponsePlugin } from 'workbox-cacheable-response'
/**
* Configures prefetching and caching of static assets as well as caching of api requests
* in the service worker.
*
* **Example**
*
* ```js
* import { configureServiceWorker } from 'react-storefront/sw'
*
* const maxAgeSeconds = 60 * 60 // 1 hour
*
* configureServiceWorker({
* api: [
* { path: '/api/[version]/p/[productId]', maxAgeSeconds },
* { path: '/api/[version]/s/[subcategoryId]', maxAgeSeconds },
* { path: '/api/[version]/', maxAgeSeconds },
* ],
* })
* ```
*
* @param {Object} config
* @param {Object} config.api An array of objects with the following properties:
* @param {Object} config.api.maxAgeSeconds The time to live in seconds for api requests
* @param {Object} config.api.paths The api paths to cache
* @param {Object} config.api.statuses Only responses with these statuses will be cached. Defaults to only caching 200s.
*/
export default function configureServiceWorker(config) {
skipWaiting()
clientsClaim()
precacheAndRoute(self.__WB_MANIFEST || [])
if (config.api) {
cacheAPIRequests(config.api)
}
}
/**
* Creates worbox routes for api routes
* @param {Object[]} api
*/
function cacheAPIRequests(api) {
for (const { path, maxAgeSeconds, statuses = [200] } of api) {
const url = new RegExp(`${self.origin}${nextRouteToRegex(path)}`, 'i')
log('Caching API route', path, url)
registerRoute(
url, // we need to remove the ^ or requests will never match
new CacheFirst({
cacheName: 'api',
plugins: [
new CacheableResponsePlugin({ statuses }),
new ExpirationPlugin({ maxAgeSeconds }),
],
}),
)
}
}
/**
* Converts next clean route syntax to a regular expression
* @param {String} route A next.js route pattern
* @return {String}
*/
function nextRouteToRegex(route) {
return `${route.replace(/\[[^\]]+\]/gi, '[^/]+')}($|\\?.*$)`
}
/**
* Stylized console.log
* @param {...any} message
*/
function log(...message) {
// istanbul ignore else
if (process.env.NODE_ENV !== 'production') {
console.log(
'%creact-storefront service-worker',
'background: #43a047; color: #ffffff; font-weight:bold; padding: 3px 5px; border-radius: 5px',
...message,
)
}
}