source: frontend/node_modules/workbox-recipes/src/imageCache.ts

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 2.5 KB
Line 
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*/
8import {warmStrategyCache} from './warmStrategyCache';
9import {registerRoute} from 'workbox-routing/registerRoute.js';
10import {CacheFirst} from 'workbox-strategies/CacheFirst.js';
11import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.js';
12import {ExpirationPlugin} from 'workbox-expiration/ExpirationPlugin.js';
13import {
14 RouteMatchCallback,
15 RouteMatchCallbackOptions,
16 WorkboxPlugin,
17} from 'workbox-core/types.js';
18
19import './_version.js';
20
21export interface ImageCacheOptions {
22 cacheName?: string;
23 matchCallback?: RouteMatchCallback;
24 maxAgeSeconds?: number;
25 maxEntries?: number;
26 plugins?: Array<WorkboxPlugin>;
27 warmCache?: Array<string>;
28}
29
30/**
31 * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images}
32 *
33 * @memberof workbox-recipes
34 *
35 * @param {Object} [options]
36 * @param {string} [options.cacheName] Name for cache. Defaults to images
37 * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image';
38 * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days
39 * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60
40 * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe
41 * @param {string[]} [options.warmCache] Paths to call to use to warm this cache
42 */
43function imageCache(options: ImageCacheOptions = {}): void {
44 const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) =>
45 request.destination === 'image';
46
47 const cacheName = options.cacheName || 'images';
48 const matchCallback = options.matchCallback || defaultMatchCallback;
49 const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60;
50 const maxEntries = options.maxEntries || 60;
51 const plugins = options.plugins || [];
52 plugins.push(
53 new CacheableResponsePlugin({
54 statuses: [0, 200],
55 }),
56 );
57 plugins.push(
58 new ExpirationPlugin({
59 maxEntries,
60 maxAgeSeconds,
61 }),
62 );
63
64 const strategy = new CacheFirst({
65 cacheName,
66 plugins,
67 });
68
69 registerRoute(matchCallback, strategy);
70
71 // Warms the cache
72 if (options.warmCache) {
73 warmStrategyCache({urls: options.warmCache, strategy});
74 }
75}
76
77export {imageCache};
Note: See TracBrowser for help on using the repository browser.