| 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 {WorkboxPlugin} from 'workbox-core/types.js';
|
|---|
| 10 | import {
|
|---|
| 11 | CacheableResponse,
|
|---|
| 12 | CacheableResponseOptions,
|
|---|
| 13 | } from './CacheableResponse.js';
|
|---|
| 14 | import './_version.js';
|
|---|
| 15 |
|
|---|
| 16 | /**
|
|---|
| 17 | * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it
|
|---|
| 18 | * easier to add in cacheability checks to requests made via Workbox's built-in
|
|---|
| 19 | * strategies.
|
|---|
| 20 | *
|
|---|
| 21 | * @memberof workbox-cacheable-response
|
|---|
| 22 | */
|
|---|
| 23 | class CacheableResponsePlugin implements WorkboxPlugin {
|
|---|
| 24 | private readonly _cacheableResponse: CacheableResponse;
|
|---|
| 25 |
|
|---|
| 26 | /**
|
|---|
| 27 | * To construct a new CacheableResponsePlugin instance you must provide at
|
|---|
| 28 | * least one of the `config` properties.
|
|---|
| 29 | *
|
|---|
| 30 | * If both `statuses` and `headers` are specified, then both conditions must
|
|---|
| 31 | * be met for the `Response` to be considered cacheable.
|
|---|
| 32 | *
|
|---|
| 33 | * @param {Object} config
|
|---|
| 34 | * @param {Array<number>} [config.statuses] One or more status codes that a
|
|---|
| 35 | * `Response` can have and be considered cacheable.
|
|---|
| 36 | * @param {Object<string,string>} [config.headers] A mapping of header names
|
|---|
| 37 | * and expected values that a `Response` can have and be considered cacheable.
|
|---|
| 38 | * If multiple headers are provided, only one needs to be present.
|
|---|
| 39 | */
|
|---|
| 40 | constructor(config: CacheableResponseOptions) {
|
|---|
| 41 | this._cacheableResponse = new CacheableResponse(config);
|
|---|
| 42 | }
|
|---|
| 43 |
|
|---|
| 44 | /**
|
|---|
| 45 | * @param {Object} options
|
|---|
| 46 | * @param {Response} options.response
|
|---|
| 47 | * @return {Response|null}
|
|---|
| 48 | * @private
|
|---|
| 49 | */
|
|---|
| 50 | cacheWillUpdate: WorkboxPlugin['cacheWillUpdate'] = async ({response}) => {
|
|---|
| 51 | if (this._cacheableResponse.isResponseCacheable(response)) {
|
|---|
| 52 | return response;
|
|---|
| 53 | }
|
|---|
| 54 | return null;
|
|---|
| 55 | };
|
|---|
| 56 | }
|
|---|
| 57 |
|
|---|
| 58 | export {CacheableResponsePlugin};
|
|---|