| 1 | /*
|
|---|
| 2 | Copyright 2020 Google LLC
|
|---|
| 3 |
|
|---|
| 4 | Use of this source code is governed by an MIT-style
|
|---|
| 5 | license that can be found in the LICENSE file or at
|
|---|
| 6 | https://opensource.org/licenses/MIT.
|
|---|
| 7 | */
|
|---|
| 8 | import { warmStrategyCache } from './warmStrategyCache';
|
|---|
| 9 | import { registerRoute } from 'workbox-routing/registerRoute.js';
|
|---|
| 10 | import { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';
|
|---|
| 11 | import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';
|
|---|
| 12 | import './_version.js';
|
|---|
| 13 | /**
|
|---|
| 14 | * An implementation of a page caching recipe with a network timeout
|
|---|
| 15 | *
|
|---|
| 16 | * @memberof workbox-recipes
|
|---|
| 17 | *
|
|---|
| 18 | * @param {Object} [options]
|
|---|
| 19 | * @param {string} [options.cacheName] Name for cache. Defaults to pages
|
|---|
| 20 | * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate';
|
|---|
| 21 | * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3
|
|---|
| 22 | * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe
|
|---|
| 23 | * @param {string[]} [options.warmCache] Paths to call to use to warm this cache
|
|---|
| 24 | */
|
|---|
| 25 | function pageCache(options = {}) {
|
|---|
| 26 | const defaultMatchCallback = ({ request }) => request.mode === 'navigate';
|
|---|
| 27 | const cacheName = options.cacheName || 'pages';
|
|---|
| 28 | const matchCallback = options.matchCallback || defaultMatchCallback;
|
|---|
| 29 | const networkTimeoutSeconds = options.networkTimeoutSeconds || 3;
|
|---|
| 30 | const plugins = options.plugins || [];
|
|---|
| 31 | plugins.push(new CacheableResponsePlugin({
|
|---|
| 32 | statuses: [0, 200],
|
|---|
| 33 | }));
|
|---|
| 34 | const strategy = new NetworkFirst({
|
|---|
| 35 | networkTimeoutSeconds,
|
|---|
| 36 | cacheName,
|
|---|
| 37 | plugins,
|
|---|
| 38 | });
|
|---|
| 39 | // Registers the route
|
|---|
| 40 | registerRoute(matchCallback, strategy);
|
|---|
| 41 | // Warms the cache
|
|---|
| 42 | if (options.warmCache) {
|
|---|
| 43 | warmStrategyCache({ urls: options.warmCache, strategy });
|
|---|
| 44 | }
|
|---|
| 45 | }
|
|---|
| 46 | export { pageCache };
|
|---|