| 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 { Strategy } from './Strategy.js';
|
|---|
| 12 | import { messages } from './utils/messages.js';
|
|---|
| 13 | import './_version.js';
|
|---|
| 14 | /**
|
|---|
| 15 | * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only)
|
|---|
| 16 | * request strategy.
|
|---|
| 17 | *
|
|---|
| 18 | * This class is useful if you want to take advantage of any
|
|---|
| 19 | * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).
|
|---|
| 20 | *
|
|---|
| 21 | * If there is no cache match, this will throw a `WorkboxError` exception.
|
|---|
| 22 | *
|
|---|
| 23 | * @extends workbox-strategies.Strategy
|
|---|
| 24 | * @memberof workbox-strategies
|
|---|
| 25 | */
|
|---|
| 26 | class CacheOnly extends Strategy {
|
|---|
| 27 | /**
|
|---|
| 28 | * @private
|
|---|
| 29 | * @param {Request|string} request A request to run this strategy for.
|
|---|
| 30 | * @param {workbox-strategies.StrategyHandler} handler The event that
|
|---|
| 31 | * triggered the request.
|
|---|
| 32 | * @return {Promise<Response>}
|
|---|
| 33 | */
|
|---|
| 34 | async _handle(request, handler) {
|
|---|
| 35 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 36 | assert.isInstance(request, Request, {
|
|---|
| 37 | moduleName: 'workbox-strategies',
|
|---|
| 38 | className: this.constructor.name,
|
|---|
| 39 | funcName: 'makeRequest',
|
|---|
| 40 | paramName: 'request',
|
|---|
| 41 | });
|
|---|
| 42 | }
|
|---|
| 43 | const response = await handler.cacheMatch(request);
|
|---|
| 44 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 45 | logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
|
|---|
| 46 | if (response) {
|
|---|
| 47 | logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`);
|
|---|
| 48 | messages.printFinalResponse(response);
|
|---|
| 49 | }
|
|---|
| 50 | else {
|
|---|
| 51 | logger.log(`No response found in the '${this.cacheName}' cache.`);
|
|---|
| 52 | }
|
|---|
| 53 | logger.groupEnd();
|
|---|
| 54 | }
|
|---|
| 55 | if (!response) {
|
|---|
| 56 | throw new WorkboxError('no-response', { url: request.url });
|
|---|
| 57 | }
|
|---|
| 58 | return response;
|
|---|
| 59 | }
|
|---|
| 60 | }
|
|---|
| 61 | export { CacheOnly };
|
|---|