imageCache.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. Copyright 2020 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import { warmStrategyCache } from './warmStrategyCache';
  8. import { registerRoute } from 'workbox-routing/registerRoute.js';
  9. import { CacheFirst } from 'workbox-strategies/CacheFirst.js';
  10. import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';
  11. import { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';
  12. import './_version.js';
  13. /**
  14. * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images}
  15. *
  16. * @memberof workbox-recipes
  17. *
  18. * @param {Object} [options]
  19. * @param {string} [options.cacheName] Name for cache. Defaults to images
  20. * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image';
  21. * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days
  22. * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60
  23. * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe
  24. * @param {string[]} [options.warmCache] Paths to call to use to warm this cache
  25. */
  26. function imageCache(options = {}) {
  27. const defaultMatchCallback = ({ request }) => request.destination === 'image';
  28. const cacheName = options.cacheName || 'images';
  29. const matchCallback = options.matchCallback || defaultMatchCallback;
  30. const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60;
  31. const maxEntries = options.maxEntries || 60;
  32. const plugins = options.plugins || [];
  33. plugins.push(new CacheableResponsePlugin({
  34. statuses: [0, 200],
  35. }));
  36. plugins.push(new ExpirationPlugin({
  37. maxEntries,
  38. maxAgeSeconds,
  39. }));
  40. const strategy = new CacheFirst({
  41. cacheName,
  42. plugins,
  43. });
  44. registerRoute(matchCallback, strategy);
  45. // Warms the cache
  46. if (options.warmCache) {
  47. warmStrategyCache({ urls: options.warmCache, strategy });
  48. }
  49. }
  50. export { imageCache };