1. function matchHeaders(headers, patterns) {
  2. for (const pattern of patterns) {
  3. if (matches(headers, pattern)) {
  4. return pattern; // Return the first matching pattern
  5. }
  6. }
  7. return null; // No match found
  8. }
  9. function matches(headers, pattern) {
  10. if (typeof pattern === 'string') {
  11. // Simple string match
  12. if (headers.hasOwnProperty(pattern)) {
  13. return true;
  14. }
  15. } else if (Array.isArray(pattern)) {
  16. // Check if a header exists with one of the specified names
  17. if (pattern.some(header => headers.hasOwnProperty(header))) {
  18. return true;
  19. }
  20. } else if (typeof pattern === 'object') {
  21. // More complex pattern matching (e.g., checking values)
  22. if (pattern.key && pattern.value && headers.hasOwnProperty(pattern.key) && headers[pattern.key] === pattern.value) {
  23. return true;
  24. }
  25. }
  26. return false;
  27. }
  28. // Example Usage:
  29. // Define some patterns
  30. const patterns = [
  31. "Content-Type",
  32. ["Accept", "application/json"],
  33. { key: "X-Custom-Header", value: "testvalue" }
  34. ];
  35. // Example headers
  36. const headers1 = {
  37. "Content-Type": "application/json",
  38. "Accept": "application/json",
  39. "X-Custom-Header": "testvalue"
  40. };
  41. const headers2 = {
  42. "Content-Type": "text/html",
  43. "Accept": "text/html"
  44. };
  45. console.log(matchHeaders(headers1, patterns)); // Output: Content-Type
  46. console.log(matchHeaders(headers2, patterns)); // Output: null
  47. console.log(matchHeaders(headers1, [ "Accept", "application/json"])); // Output: Accept
  48. console.log(matchHeaders(headers1, { key: "X-Custom-Header", value: "testvalue" })); // Output: X-Custom-Header

Add your comment