responsesAreSame.mjs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
  8. import {logger} from 'workbox-core/_private/logger.mjs';
  9. import './_version.mjs';
  10. /**
  11. * Given two `Response's`, compares several header values to see if they are
  12. * the same or not.
  13. *
  14. * @param {Response} firstResponse
  15. * @param {Response} secondResponse
  16. * @param {Array<string>} headersToCheck
  17. * @return {boolean}
  18. *
  19. * @memberof workbox.broadcastUpdate
  20. * @private
  21. */
  22. const responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {
  23. if (process.env.NODE_ENV !== 'production') {
  24. if (!(firstResponse instanceof Response &&
  25. secondResponse instanceof Response)) {
  26. throw new WorkboxError('invalid-responses-are-same-args');
  27. }
  28. }
  29. const atLeastOneHeaderAvailable = headersToCheck.some((header) => {
  30. return firstResponse.headers.has(header) &&
  31. secondResponse.headers.has(header);
  32. });
  33. if (!atLeastOneHeaderAvailable) {
  34. if (process.env.NODE_ENV !== 'production') {
  35. logger.warn(`Unable to determine where the response has been updated ` +
  36. `because none of the headers that would be checked are present.`);
  37. logger.debug(`Attempting to compare the following: `,
  38. firstResponse, secondResponse, headersToCheck);
  39. }
  40. // Just return true, indicating the that responses are the same, since we
  41. // can't determine otherwise.
  42. return true;
  43. }
  44. return headersToCheck.every((header) => {
  45. const headerStateComparison = firstResponse.headers.has(header) ===
  46. secondResponse.headers.has(header);
  47. const headerValueComparison = firstResponse.headers.get(header) ===
  48. secondResponse.headers.get(header);
  49. return headerStateComparison && headerValueComparison;
  50. });
  51. };
  52. export {responsesAreSame};