CacheOnly.ts 3.7 KB

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