responsesAreSame.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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.js';
  8. import { logger } from 'workbox-core/_private/logger.js';
  9. import './_version.js';
  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 module:workbox-broadcast-update
  20. */
  21. const responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {
  22. if (process.env.NODE_ENV !== 'production') {
  23. if (!(firstResponse instanceof Response &&
  24. secondResponse instanceof Response)) {
  25. throw new WorkboxError('invalid-responses-are-same-args');
  26. }
  27. }
  28. const atLeastOneHeaderAvailable = headersToCheck.some((header) => {
  29. return firstResponse.headers.has(header) &&
  30. secondResponse.headers.has(header);
  31. });
  32. if (!atLeastOneHeaderAvailable) {
  33. if (process.env.NODE_ENV !== 'production') {
  34. logger.warn(`Unable to determine where the response has been updated ` +
  35. `because none of the headers that would be checked are present.`);
  36. logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);
  37. }
  38. // Just return true, indicating the that responses are the same, since we
  39. // can't determine otherwise.
  40. return true;
  41. }
  42. return headersToCheck.every((header) => {
  43. const headerStateComparison = firstResponse.headers.has(header) ===
  44. secondResponse.headers.has(header);
  45. const headerValueComparison = firstResponse.headers.get(header) ===
  46. secondResponse.headers.get(header);
  47. return headerStateComparison && headerValueComparison;
  48. });
  49. };
  50. export { responsesAreSame };