RangeRequestsPlugin.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 { createPartialResponse } from './createPartialResponse.js';
  8. import './_version.js';
  9. /**
  10. * The range request plugin makes it easy for a request with a 'Range' header to
  11. * be fulfilled by a cached response.
  12. *
  13. * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback
  14. * and returning the appropriate subset of the cached response body.
  15. *
  16. * @memberof module:workbox-range-requests
  17. */
  18. class RangeRequestsPlugin {
  19. constructor() {
  20. /**
  21. * @param {Object} options
  22. * @param {Request} options.request The original request, which may or may not
  23. * contain a Range: header.
  24. * @param {Response} options.cachedResponse The complete cached response.
  25. * @return {Promise<Response>} If request contains a 'Range' header, then a
  26. * new response with status 206 whose body is a subset of `cachedResponse` is
  27. * returned. Otherwise, `cachedResponse` is returned as-is.
  28. *
  29. * @private
  30. */
  31. this.cachedResponseWillBeUsed = async ({ request, cachedResponse }) => {
  32. // Only return a sliced response if there's something valid in the cache,
  33. // and there's a Range: header in the request.
  34. if (cachedResponse && request.headers.has('range')) {
  35. return await createPartialResponse(request, cachedResponse);
  36. }
  37. // If there was no Range: header, or if cachedResponse wasn't valid, just
  38. // pass it through as-is.
  39. return cachedResponse;
  40. };
  41. }
  42. }
  43. export { RangeRequestsPlugin };