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