CacheOnly.mjs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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.mjs';
  8. import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
  9. import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.mjs';
  10. import {logger} from 'workbox-core/_private/logger.mjs';
  11. import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
  12. import {messages} from './utils/messages.mjs';
  13. import './_version.mjs';
  14. /**
  15. * An implementation of a
  16. * [cache-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only}
  17. * request strategy.
  18. *
  19. * This class is useful if you want to take advantage of any
  20. * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}.
  21. *
  22. * If there is no cache match, this will throw a `WorkboxError` exception.
  23. *
  24. * @memberof workbox.strategies
  25. */
  26. class CacheOnly {
  27. /**
  28. * @param {Object} options
  29. * @param {string} options.cacheName Cache name to store and retrieve
  30. * requests. Defaults to cache names provided by
  31. * [workbox-core]{@link workbox.core.cacheNames}.
  32. * @param {Array<Object>} options.plugins [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  33. * to use in conjunction with this caching strategy.
  34. * @param {Object} options.matchOptions [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)
  35. */
  36. constructor(options = {}) {
  37. this._cacheName = cacheNames.getRuntimeName(options.cacheName);
  38. this._plugins = options.plugins || [];
  39. this._matchOptions = options.matchOptions || null;
  40. }
  41. /**
  42. * This method will perform a request strategy and follows an API that
  43. * will work with the
  44. * [Workbox Router]{@link workbox.routing.Router}.
  45. *
  46. * @param {Object} options
  47. * @param {Request} options.request The request to run this strategy for.
  48. * @param {Event} [options.event] The event that triggered the request.
  49. * @return {Promise<Response>}
  50. */
  51. async handle({event, request}) {
  52. return this.makeRequest({
  53. event,
  54. request: request || event.request,
  55. });
  56. }
  57. /**
  58. * This method can be used to perform a make a standalone request outside the
  59. * context of the [Workbox Router]{@link workbox.routing.Router}.
  60. *
  61. * See "[Advanced Recipes](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests)"
  62. * for more usage information.
  63. *
  64. * @param {Object} options
  65. * @param {Request|string} options.request Either a
  66. * [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request}
  67. * object, or a string URL, corresponding to the request to be made.
  68. * @param {FetchEvent} [options.event] If provided, `event.waitUntil()` will
  69. * be called automatically to extend the service worker's lifetime.
  70. * @return {Promise<Response>}
  71. */
  72. async makeRequest({event, request}) {
  73. if (typeof request === 'string') {
  74. request = new Request(request);
  75. }
  76. if (process.env.NODE_ENV !== 'production') {
  77. assert.isInstance(request, Request, {
  78. moduleName: 'workbox-strategies',
  79. className: 'CacheOnly',
  80. funcName: 'makeRequest',
  81. paramName: 'request',
  82. });
  83. }
  84. const response = await cacheWrapper.match({
  85. cacheName: this._cacheName,
  86. request,
  87. event,
  88. matchOptions: this._matchOptions,
  89. plugins: this._plugins,
  90. });
  91. if (process.env.NODE_ENV !== 'production') {
  92. logger.groupCollapsed(
  93. messages.strategyStart('CacheOnly', request));
  94. if (response) {
  95. logger.log(`Found a cached response in the '${this._cacheName}'` +
  96. ` cache.`);
  97. messages.printFinalResponse(response);
  98. } else {
  99. logger.log(`No response found in the '${this._cacheName}' cache.`);
  100. }
  101. logger.groupEnd();
  102. }
  103. if (!response) {
  104. throw new WorkboxError('no-response', {url: request.url});
  105. }
  106. return response;
  107. }
  108. }
  109. export {CacheOnly};