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