You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CacheFirst.mjs 6.6 KiB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. /*
  2. Copyright 2018 Google Inc. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. import {assert} from 'workbox-core/_private/assert.mjs';
  14. import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
  15. import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.mjs';
  16. import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.mjs';
  17. import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.mjs';
  18. import {logger} from 'workbox-core/_private/logger.mjs';
  19. import messages from './utils/messages.mjs';
  20. import './_version.mjs';
  21. /**
  22. * An implementation of a [cache-first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network}
  23. * request strategy.
  24. *
  25. * A cache first strategy is useful for assets that have been revisioned,
  26. * such as URLs like `/styles/example.a8f5f1.css`, since they
  27. * can be cached for long periods of time.
  28. *
  29. * @memberof workbox.strategies
  30. */
  31. class CacheFirst {
  32. /**
  33. * @param {Object} options
  34. * @param {string} options.cacheName Cache name to store and retrieve
  35. * requests. Defaults to cache names provided by
  36. * [workbox-core]{@link workbox.core.cacheNames}.
  37. * @param {Array<Object>} options.plugins [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  38. * to use in conjunction with this caching strategy.
  39. * @param {Object} options.fetchOptions Values passed along to the
  40. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  41. * of all fetch() requests made by this strategy.
  42. * @param {Object} options.matchOptions [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)
  43. */
  44. constructor(options = {}) {
  45. this._cacheName = cacheNames.getRuntimeName(options.cacheName);
  46. this._plugins = options.plugins || [];
  47. this._fetchOptions = options.fetchOptions || null;
  48. this._matchOptions = options.matchOptions || null;
  49. }
  50. /**
  51. * This method will perform a request strategy and follows an API that
  52. * will work with the
  53. * [Workbox Router]{@link workbox.routing.Router}.
  54. *
  55. * @param {Object} options
  56. * @param {FetchEvent} options.event The fetch event to run this strategy
  57. * against.
  58. * @return {Promise<Response>}
  59. */
  60. async handle({event}) {
  61. if (process.env.NODE_ENV !== 'production') {
  62. assert.isInstance(event, FetchEvent, {
  63. moduleName: 'workbox-strategies',
  64. className: 'CacheFirst',
  65. funcName: 'handle',
  66. paramName: 'event',
  67. });
  68. }
  69. return this.makeRequest({
  70. event,
  71. request: event.request,
  72. });
  73. }
  74. /**
  75. * This method can be used to perform a make a standalone request outside the
  76. * context of the [Workbox Router]{@link workbox.routing.Router}.
  77. *
  78. * See "[Advanced Recipes](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests)"
  79. * for more usage information.
  80. *
  81. * @param {Object} options
  82. * @param {Request|string} options.request Either a
  83. * [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request}
  84. * object, or a string URL, corresponding to the request to be made.
  85. * @param {FetchEvent} [options.event] If provided, `event.waitUntil()` will
  86. be called automatically to extend the service worker's lifetime.
  87. * @return {Promise<Response>}
  88. */
  89. async makeRequest({event, request}) {
  90. const logs = [];
  91. if (typeof request === 'string') {
  92. request = new Request(request);
  93. }
  94. if (process.env.NODE_ENV !== 'production') {
  95. assert.isInstance(request, Request, {
  96. moduleName: 'workbox-strategies',
  97. className: 'CacheFirst',
  98. funcName: 'makeRequest',
  99. paramName: 'request',
  100. });
  101. }
  102. let response = await cacheWrapper.match({
  103. cacheName: this._cacheName,
  104. request,
  105. event,
  106. matchOptions: this._matchOptions,
  107. plugins: this._plugins,
  108. });
  109. let error;
  110. if (!response) {
  111. if (process.env.NODE_ENV !== 'production') {
  112. logs.push(
  113. `No response found in the '${this._cacheName}' cache. ` +
  114. `Will respond with a network request.`);
  115. }
  116. try {
  117. response = await this._getFromNetwork(request, event);
  118. } catch (err) {
  119. error = err;
  120. }
  121. if (process.env.NODE_ENV !== 'production') {
  122. if (response) {
  123. logs.push(`Got response from network.`);
  124. } else {
  125. logs.push(`Unable to get a response from the network.`);
  126. }
  127. }
  128. } else {
  129. if (process.env.NODE_ENV !== 'production') {
  130. logs.push(
  131. `Found a cached response in the '${this._cacheName}' cache.`);
  132. }
  133. }
  134. if (process.env.NODE_ENV !== 'production') {
  135. logger.groupCollapsed(
  136. messages.strategyStart('CacheFirst', request));
  137. for (let log of logs) {
  138. logger.log(log);
  139. }
  140. messages.printFinalResponse(response);
  141. logger.groupEnd();
  142. }
  143. if (error) {
  144. // Don't swallow error as we'll want it to throw and enable catch
  145. // handlers in router.
  146. throw error;
  147. }
  148. return response;
  149. }
  150. /**
  151. * Handles the network and cache part of CacheFirst.
  152. *
  153. * @param {Request} request
  154. * @param {FetchEvent} [event]
  155. * @return {Promise<Response>}
  156. *
  157. * @private
  158. */
  159. async _getFromNetwork(request, event) {
  160. const response = await fetchWrapper.fetch({
  161. request,
  162. event,
  163. fetchOptions: this._fetchOptions,
  164. plugins: this._plugins,
  165. });
  166. // Keep the service worker while we put the request to the cache
  167. const responseClone = response.clone();
  168. const cachePutPromise = cacheWrapper.put({
  169. cacheName: this._cacheName,
  170. request,
  171. response: responseClone,
  172. event,
  173. plugins: this._plugins,
  174. });
  175. if (event) {
  176. try {
  177. event.waitUntil(cachePutPromise);
  178. } catch (error) {
  179. if (process.env.NODE_ENV !== 'production') {
  180. logger.warn(`Unable to ensure service worker stays alive when ` +
  181. `updating cache for '${getFriendlyURL(event.request.url)}'.`);
  182. }
  183. }
  184. }
  185. return response;
  186. }
  187. }
  188. export {CacheFirst};