NetworkOnly.ts 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 {fetchWrapper} from 'workbox-core/_private/fetchWrapper.js';
  9. import {logger} from 'workbox-core/_private/logger.js';
  10. import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
  11. import {RouteHandlerObject, RouteHandlerCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js';
  12. import {messages} from './utils/messages.js';
  13. import './_version.js';
  14. interface NetworkFirstOptions {
  15. plugins?: WorkboxPlugin[];
  16. fetchOptions?: RequestInit;
  17. }
  18. /**
  19. * An implementation of a
  20. * [network-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-only}
  21. * request strategy.
  22. *
  23. * This class is useful if you want to take advantage of any
  24. * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}.
  25. *
  26. * If the network request fails, this will throw a `WorkboxError` exception.
  27. *
  28. * @memberof module:workbox-strategies
  29. */
  30. class NetworkOnly implements RouteHandlerObject {
  31. private readonly _plugins: WorkboxPlugin[];
  32. private readonly _fetchOptions?: RequestInit;
  33. /**
  34. * @param {Object} options
  35. * @param {string} options.cacheName Cache name to store and retrieve
  36. * requests. Defaults to cache names provided by
  37. * [workbox-core]{@link module:workbox-core.cacheNames}.
  38. * @param {Array<Object>} options.plugins [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  39. * to use in conjunction with this caching strategy.
  40. * @param {Object} options.fetchOptions Values passed along to the
  41. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  42. * of all fetch() requests made by this strategy.
  43. */
  44. constructor(options: NetworkFirstOptions = {}) {
  45. this._plugins = options.plugins || [];
  46. this._fetchOptions = options.fetchOptions;
  47. }
  48. /**
  49. * This method will perform a request strategy and follows an API that
  50. * will work with the
  51. * [Workbox Router]{@link module:workbox-routing.Router}.
  52. *
  53. * @param {Object} options
  54. * @param {Request|string} options.request The request to run this strategy for.
  55. * @param {Event} [options.event] The event that triggered the request.
  56. * @return {Promise<Response>}
  57. */
  58. async handle({event, request}: RouteHandlerCallbackOptions): Promise<Response> {
  59. if (typeof request === 'string') {
  60. request = new Request(request);
  61. }
  62. if (process.env.NODE_ENV !== 'production') {
  63. assert!.isInstance(request, Request, {
  64. moduleName: 'workbox-strategies',
  65. className: 'NetworkOnly',
  66. funcName: 'handle',
  67. paramName: 'request',
  68. });
  69. }
  70. let error;
  71. let response;
  72. try {
  73. response = await fetchWrapper.fetch({
  74. request,
  75. event,
  76. fetchOptions: this._fetchOptions,
  77. plugins: this._plugins,
  78. });
  79. } catch (err) {
  80. error = err;
  81. }
  82. if (process.env.NODE_ENV !== 'production') {
  83. logger.groupCollapsed(
  84. messages.strategyStart('NetworkOnly', request));
  85. if (response) {
  86. logger.log(`Got response from network.`);
  87. } else {
  88. logger.log(`Unable to get a response from the network.`);
  89. }
  90. messages.printFinalResponse(response);
  91. logger.groupEnd();
  92. }
  93. if (!response) {
  94. throw new WorkboxError('no-response', {url: request.url, error});
  95. }
  96. return response;
  97. }
  98. }
  99. export {NetworkOnly};