Plugin.mjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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.mjs';
  8. import './_version.mjs';
  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 workbox.rangeRequests
  17. */
  18. class Plugin {
  19. /**
  20. * @param {Object} options
  21. * @param {Request} options.request The original request, which may or may not
  22. * contain a Range: header.
  23. * @param {Response} options.cachedResponse The complete cached response.
  24. * @return {Promise<Response>} If request contains a 'Range' header, then a
  25. * new response with status 206 whose body is a subset of `cachedResponse` is
  26. * returned. Otherwise, `cachedResponse` is returned as-is.
  27. *
  28. * @private
  29. */
  30. async cachedResponseWillBeUsed({request, cachedResponse}) {
  31. // Only return a sliced response if there's something valid in the cache,
  32. // and there's a Range: header in the request.
  33. if (cachedResponse && request.headers.has('range')) {
  34. return await createPartialResponse(request, cachedResponse);
  35. }
  36. // If there was no Range: header, or if cachedResponse wasn't valid, just
  37. // pass it through as-is.
  38. return cachedResponse;
  39. }
  40. }
  41. export {Plugin};