NetworkOnly.mjs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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 {fetchWrapper} from 'workbox-core/_private/fetchWrapper.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. * [network-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-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 the network request fails, this will throw a `WorkboxError` exception.
  23. *
  24. * @memberof workbox.strategies
  25. */
  26. class NetworkOnly {
  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.fetchOptions Values passed along to the
  35. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  36. * of all fetch() requests made by this strategy.
  37. */
  38. constructor(options = {}) {
  39. this._cacheName = cacheNames.getRuntimeName(options.cacheName);
  40. this._plugins = options.plugins || [];
  41. this._fetchOptions = options.fetchOptions || null;
  42. }
  43. /**
  44. * This method will perform a request strategy and follows an API that
  45. * will work with the
  46. * [Workbox Router]{@link workbox.routing.Router}.
  47. *
  48. * @param {Object} options
  49. * @param {Request} options.request The request to run this strategy for.
  50. * @param {Event} [options.event] The event that triggered the request.
  51. * @return {Promise<Response>}
  52. */
  53. async handle({event, request}) {
  54. return this.makeRequest({
  55. event,
  56. request: request || event.request,
  57. });
  58. }
  59. /**
  60. * This method can be used to perform a make a standalone request outside the
  61. * context of the [Workbox Router]{@link workbox.routing.Router}.
  62. *
  63. * See "[Advanced Recipes](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests)"
  64. * for more usage information.
  65. *
  66. * @param {Object} options
  67. * @param {Request|string} options.request Either a
  68. * [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request}
  69. * object, or a string URL, corresponding to the request to be made.
  70. * @param {FetchEvent} [options.event] If provided, `event.waitUntil()` will
  71. * be called automatically to extend the service worker's lifetime.
  72. * @return {Promise<Response>}
  73. */
  74. async makeRequest({event, request}) {
  75. if (typeof request === 'string') {
  76. request = new Request(request);
  77. }
  78. if (process.env.NODE_ENV !== 'production') {
  79. assert.isInstance(request, Request, {
  80. moduleName: 'workbox-strategies',
  81. className: 'NetworkOnly',
  82. funcName: 'handle',
  83. paramName: 'request',
  84. });
  85. }
  86. let error;
  87. let response;
  88. try {
  89. response = await fetchWrapper.fetch({
  90. request,
  91. event,
  92. fetchOptions: this._fetchOptions,
  93. plugins: this._plugins,
  94. });
  95. } catch (err) {
  96. error = err;
  97. }
  98. if (process.env.NODE_ENV !== 'production') {
  99. logger.groupCollapsed(
  100. messages.strategyStart('NetworkOnly', request));
  101. if (response) {
  102. logger.log(`Got response from network.`);
  103. } else {
  104. logger.log(`Unable to get a response from the network.`);
  105. }
  106. messages.printFinalResponse(response);
  107. logger.groupEnd();
  108. }
  109. if (!response) {
  110. throw new WorkboxError('no-response', {url: request.url, error});
  111. }
  112. return response;
  113. }
  114. }
  115. export {NetworkOnly};