CacheOnly.js 2.2 KB

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