| 1 | /*
|
|---|
| 2 | Copyright 2018 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 |
|
|---|
| 9 | import {assert} from 'workbox-core/_private/assert.js';
|
|---|
| 10 | import {logger} from 'workbox-core/_private/logger.js';
|
|---|
| 11 | import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
|
|---|
| 12 |
|
|---|
| 13 | import {cacheOkAndOpaquePlugin} from './plugins/cacheOkAndOpaquePlugin.js';
|
|---|
| 14 | import {Strategy, StrategyOptions} from './Strategy.js';
|
|---|
| 15 | import {StrategyHandler} from './StrategyHandler.js';
|
|---|
| 16 | import {messages} from './utils/messages.js';
|
|---|
| 17 | import './_version.js';
|
|---|
| 18 |
|
|---|
| 19 | /**
|
|---|
| 20 | * An implementation of a
|
|---|
| 21 | * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate)
|
|---|
| 22 | * request strategy.
|
|---|
| 23 | *
|
|---|
| 24 | * Resources are requested from both the cache and the network in parallel.
|
|---|
| 25 | * The strategy will respond with the cached version if available, otherwise
|
|---|
| 26 | * wait for the network response. The cache is updated with the network response
|
|---|
| 27 | * with each successful request.
|
|---|
| 28 | *
|
|---|
| 29 | * By default, this strategy will cache responses with a 200 status code as
|
|---|
| 30 | * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
|
|---|
| 31 | * Opaque responses are cross-origin requests where the response doesn't
|
|---|
| 32 | * support [CORS](https://enable-cors.org/).
|
|---|
| 33 | *
|
|---|
| 34 | * If the network request fails, and there is no cache match, this will throw
|
|---|
| 35 | * a `WorkboxError` exception.
|
|---|
| 36 | *
|
|---|
| 37 | * @extends workbox-strategies.Strategy
|
|---|
| 38 | * @memberof workbox-strategies
|
|---|
| 39 | */
|
|---|
| 40 | class StaleWhileRevalidate extends Strategy {
|
|---|
| 41 | /**
|
|---|
| 42 | * @param {Object} [options]
|
|---|
| 43 | * @param {string} [options.cacheName] Cache name to store and retrieve
|
|---|
| 44 | * requests. Defaults to cache names provided by
|
|---|
| 45 | * {@link workbox-core.cacheNames}.
|
|---|
| 46 | * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
|
|---|
| 47 | * to use in conjunction with this caching strategy.
|
|---|
| 48 | * @param {Object} [options.fetchOptions] Values passed along to the
|
|---|
| 49 | * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
|
|---|
| 50 | * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
|
|---|
| 51 | * `fetch()` requests made by this strategy.
|
|---|
| 52 | * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)
|
|---|
| 53 | */
|
|---|
| 54 | constructor(options: StrategyOptions = {}) {
|
|---|
| 55 | super(options);
|
|---|
| 56 |
|
|---|
| 57 | // If this instance contains no plugins with a 'cacheWillUpdate' callback,
|
|---|
| 58 | // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.
|
|---|
| 59 | if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {
|
|---|
| 60 | this.plugins.unshift(cacheOkAndOpaquePlugin);
|
|---|
| 61 | }
|
|---|
| 62 | }
|
|---|
| 63 |
|
|---|
| 64 | /**
|
|---|
| 65 | * @private
|
|---|
| 66 | * @param {Request|string} request A request to run this strategy for.
|
|---|
| 67 | * @param {workbox-strategies.StrategyHandler} handler The event that
|
|---|
| 68 | * triggered the request.
|
|---|
| 69 | * @return {Promise<Response>}
|
|---|
| 70 | */
|
|---|
| 71 | async _handle(request: Request, handler: StrategyHandler): Promise<Response> {
|
|---|
| 72 | const logs = [];
|
|---|
| 73 |
|
|---|
| 74 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 75 | assert!.isInstance(request, Request, {
|
|---|
| 76 | moduleName: 'workbox-strategies',
|
|---|
| 77 | className: this.constructor.name,
|
|---|
| 78 | funcName: 'handle',
|
|---|
| 79 | paramName: 'request',
|
|---|
| 80 | });
|
|---|
| 81 | }
|
|---|
| 82 |
|
|---|
| 83 | const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {
|
|---|
| 84 | // Swallow this error because a 'no-response' error will be thrown in
|
|---|
| 85 | // main handler return flow. This will be in the `waitUntil()` flow.
|
|---|
| 86 | });
|
|---|
| 87 | void handler.waitUntil(fetchAndCachePromise);
|
|---|
| 88 |
|
|---|
| 89 | let response = await handler.cacheMatch(request);
|
|---|
| 90 |
|
|---|
| 91 | let error;
|
|---|
| 92 | if (response) {
|
|---|
| 93 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 94 | logs.push(
|
|---|
| 95 | `Found a cached response in the '${this.cacheName}'` +
|
|---|
| 96 | ` cache. Will update with the network response in the background.`,
|
|---|
| 97 | );
|
|---|
| 98 | }
|
|---|
| 99 | } else {
|
|---|
| 100 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 101 | logs.push(
|
|---|
| 102 | `No response found in the '${this.cacheName}' cache. ` +
|
|---|
| 103 | `Will wait for the network response.`,
|
|---|
| 104 | );
|
|---|
| 105 | }
|
|---|
| 106 | try {
|
|---|
| 107 | // NOTE(philipwalton): Really annoying that we have to type cast here.
|
|---|
| 108 | // https://github.com/microsoft/TypeScript/issues/20006
|
|---|
| 109 | response = (await fetchAndCachePromise) as Response | undefined;
|
|---|
| 110 | } catch (err) {
|
|---|
| 111 | if (err instanceof Error) {
|
|---|
| 112 | error = err;
|
|---|
| 113 | }
|
|---|
| 114 | }
|
|---|
| 115 | }
|
|---|
| 116 |
|
|---|
| 117 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 118 | logger.groupCollapsed(
|
|---|
| 119 | messages.strategyStart(this.constructor.name, request),
|
|---|
| 120 | );
|
|---|
| 121 | for (const log of logs) {
|
|---|
| 122 | logger.log(log);
|
|---|
| 123 | }
|
|---|
| 124 | messages.printFinalResponse(response);
|
|---|
| 125 | logger.groupEnd();
|
|---|
| 126 | }
|
|---|
| 127 |
|
|---|
| 128 | if (!response) {
|
|---|
| 129 | throw new WorkboxError('no-response', {url: request.url, error});
|
|---|
| 130 | }
|
|---|
| 131 | return response;
|
|---|
| 132 | }
|
|---|
| 133 | }
|
|---|
| 134 |
|
|---|
| 135 | export {StaleWhileRevalidate};
|
|---|