function matchHeaders(headers, patterns) {
for (const pattern of patterns) {
if (matches(headers, pattern)) {
return pattern; // Return the first matching pattern
}
}
return null; // No match found
}
function matches(headers, pattern) {
if (typeof pattern === 'string') {
// Simple string match
if (headers.hasOwnProperty(pattern)) {
return true;
}
} else if (Array.isArray(pattern)) {
// Check if a header exists with one of the specified names
if (pattern.some(header => headers.hasOwnProperty(header))) {
return true;
}
} else if (typeof pattern === 'object') {
// More complex pattern matching (e.g., checking values)
if (pattern.key && pattern.value && headers.hasOwnProperty(pattern.key) && headers[pattern.key] === pattern.value) {
return true;
}
}
return false;
}
// Example Usage:
// Define some patterns
const patterns = [
"Content-Type",
["Accept", "application/json"],
{ key: "X-Custom-Header", value: "testvalue" }
];
// Example headers
const headers1 = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Custom-Header": "testvalue"
};
const headers2 = {
"Content-Type": "text/html",
"Accept": "text/html"
};
console.log(matchHeaders(headers1, patterns)); // Output: Content-Type
console.log(matchHeaders(headers2, patterns)); // Output: null
console.log(matchHeaders(headers1, [ "Accept", "application/json"])); // Output: Accept
console.log(matchHeaders(headers1, { key: "X-Custom-Header", value: "testvalue" })); // Output: X-Custom-Header
Add your comment