| 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 { CacheFirst } from 'workbox-strategies/CacheFirst.js';
|
|---|
| 11 | import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';
|
|---|
| 12 | import { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';
|
|---|
| 13 | import './_version.js';
|
|---|
| 14 | /**
|
|---|
| 15 | * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images}
|
|---|
| 16 | *
|
|---|
| 17 | * @memberof workbox-recipes
|
|---|
| 18 | *
|
|---|
| 19 | * @param {Object} [options]
|
|---|
| 20 | * @param {string} [options.cacheName] Name for cache. Defaults to images
|
|---|
| 21 | * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image';
|
|---|
| 22 | * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days
|
|---|
| 23 | * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60
|
|---|
| 24 | * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe
|
|---|
| 25 | * @param {string[]} [options.warmCache] Paths to call to use to warm this cache
|
|---|
| 26 | */
|
|---|
| 27 | function imageCache(options = {}) {
|
|---|
| 28 | const defaultMatchCallback = ({ request }) => request.destination === 'image';
|
|---|
| 29 | const cacheName = options.cacheName || 'images';
|
|---|
| 30 | const matchCallback = options.matchCallback || defaultMatchCallback;
|
|---|
| 31 | const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60;
|
|---|
| 32 | const maxEntries = options.maxEntries || 60;
|
|---|
| 33 | const plugins = options.plugins || [];
|
|---|
| 34 | plugins.push(new CacheableResponsePlugin({
|
|---|
| 35 | statuses: [0, 200],
|
|---|
| 36 | }));
|
|---|
| 37 | plugins.push(new ExpirationPlugin({
|
|---|
| 38 | maxEntries,
|
|---|
| 39 | maxAgeSeconds,
|
|---|
| 40 | }));
|
|---|
| 41 | const strategy = new CacheFirst({
|
|---|
| 42 | cacheName,
|
|---|
| 43 | plugins,
|
|---|
| 44 | });
|
|---|
| 45 | registerRoute(matchCallback, strategy);
|
|---|
| 46 | // Warms the cache
|
|---|
| 47 | if (options.warmCache) {
|
|---|
| 48 | warmStrategyCache({ urls: options.warmCache, strategy });
|
|---|
| 49 | }
|
|---|
| 50 | }
|
|---|
| 51 | export { imageCache };
|
|---|