CacheOnly.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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
  15. * [cache-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only}
  16. * request strategy.
  17. *
  18. * This class is useful if you want to take advantage of any
  19. * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}.
  20. *
  21. * If there is no cache match, this will throw a `WorkboxError` exception.
  22. *
  23. * @extends module:workbox-strategies.Strategy
  24. * @memberof module: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 {module: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 };