copyResponse.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. Copyright 2019 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 { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js';
  8. import './_version.js';
  9. /**
  10. * Allows developers to copy a response and modify its `headers`, `status`,
  11. * or `statusText` values (the values settable via a
  12. * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}
  13. * object in the constructor).
  14. * To modify these values, pass a function as the second argument. That
  15. * function will be invoked with a single object with the response properties
  16. * `{headers, status, statusText}`. The return value of this function will
  17. * be used as the `ResponseInit` for the new `Response`. To change the values
  18. * either modify the passed parameter(s) and return it, or return a totally
  19. * new object.
  20. *
  21. * @param {Response} response
  22. * @param {Function} modifier
  23. * @memberof module:workbox-core
  24. */
  25. async function copyResponse(response, modifier) {
  26. const clonedResponse = response.clone();
  27. // Create a fresh `ResponseInit` object by cloning the headers.
  28. const responseInit = {
  29. headers: new Headers(clonedResponse.headers),
  30. status: clonedResponse.status,
  31. statusText: clonedResponse.statusText,
  32. };
  33. // Apply any user modifications.
  34. const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
  35. // Create the new response from the body stream and `ResponseInit`
  36. // modifications. Note: not all browsers support the Response.body stream,
  37. // so fall back to reading the entire body into memory as a blob.
  38. const body = canConstructResponseFromBodyStream() ?
  39. clonedResponse.body : await clonedResponse.blob();
  40. return new Response(body, modifiedResponseInit);
  41. }
  42. export { copyResponse };