| 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 |
|
|---|
| 9 | import {WorkboxPlugin} from 'workbox-core/types.js';
|
|---|
| 10 |
|
|---|
| 11 | import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js';
|
|---|
| 12 | import {PrecacheController} from './PrecacheController.js';
|
|---|
| 13 |
|
|---|
| 14 | import './_version.js';
|
|---|
| 15 |
|
|---|
| 16 | /**
|
|---|
| 17 | * `PrecacheFallbackPlugin` allows you to specify an "offline fallback"
|
|---|
| 18 | * response to be used when a given strategy is unable to generate a response.
|
|---|
| 19 | *
|
|---|
| 20 | * It does this by intercepting the `handlerDidError` plugin callback
|
|---|
| 21 | * and returning a precached response, taking the expected revision parameter
|
|---|
| 22 | * into account automatically.
|
|---|
| 23 | *
|
|---|
| 24 | * Unless you explicitly pass in a `PrecacheController` instance to the
|
|---|
| 25 | * constructor, the default instance will be used. Generally speaking, most
|
|---|
| 26 | * developers will end up using the default.
|
|---|
| 27 | *
|
|---|
| 28 | * @memberof workbox-precaching
|
|---|
| 29 | */
|
|---|
| 30 | class PrecacheFallbackPlugin implements WorkboxPlugin {
|
|---|
| 31 | private readonly _fallbackURL: string;
|
|---|
| 32 | private readonly _precacheController: PrecacheController;
|
|---|
| 33 |
|
|---|
| 34 | /**
|
|---|
| 35 | * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL.
|
|---|
| 36 | *
|
|---|
| 37 | * @param {Object} config
|
|---|
| 38 | * @param {string} config.fallbackURL A precached URL to use as the fallback
|
|---|
| 39 | * if the associated strategy can't generate a response.
|
|---|
| 40 | * @param {PrecacheController} [config.precacheController] An optional
|
|---|
| 41 | * PrecacheController instance. If not provided, the default
|
|---|
| 42 | * PrecacheController will be used.
|
|---|
| 43 | */
|
|---|
| 44 | constructor({
|
|---|
| 45 | fallbackURL,
|
|---|
| 46 | precacheController,
|
|---|
| 47 | }: {
|
|---|
| 48 | fallbackURL: string;
|
|---|
| 49 | precacheController?: PrecacheController;
|
|---|
| 50 | }) {
|
|---|
| 51 | this._fallbackURL = fallbackURL;
|
|---|
| 52 | this._precacheController =
|
|---|
| 53 | precacheController || getOrCreatePrecacheController();
|
|---|
| 54 | }
|
|---|
| 55 |
|
|---|
| 56 | /**
|
|---|
| 57 | * @return {Promise<Response>} The precache response for the fallback URL.
|
|---|
| 58 | *
|
|---|
| 59 | * @private
|
|---|
| 60 | */
|
|---|
| 61 | handlerDidError: WorkboxPlugin['handlerDidError'] = () =>
|
|---|
| 62 | this._precacheController.matchPrecache(this._fallbackURL);
|
|---|
| 63 | }
|
|---|
| 64 |
|
|---|
| 65 | export {PrecacheFallbackPlugin};
|
|---|