/**
* Streams request headers with a timeout for hypothesis validation.
* @param {XMLHttpRequest} xhr - The XMLHttpRequest object.
* @param {object} expectedHeaders - An object containing the expected headers and their values.
* @param {number} timeout - The timeout in milliseconds.
* @returns {Promise<object>} - A promise that resolves with the expected headers if all match, or rejects with an error if the timeout is reached.
*/
async function streamRequestHeaders(xhr, expectedHeaders, timeout) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const headersToValidate = Object.keys(expectedHeaders);
let headersReceived = {};
xhr.onheaders = function(e) {
//Handle header events.
for (const headerName in e) {
if (headersToValidate.includes(headerName)) {
headersReceived[headerName] = e[headerName];
}
}
};
xhr.timeout = timeout; //Set timeout on the request
xhr.onload = function() {
if (Date.now() - startTime < timeout) {
// Check if all expected headers are present and match.
let allHeadersMatch = true;
for (const headerName of headersToValidate) {
if (headersReceived[headerName] !== expectedHeaders[headerName]) {
allHeadersMatch = false;
break;
}
}
if (allHeadersMatch) {
resolve(headersReceived);
} else {
reject(new Error("Request headers do not match expected headers."));
}
} else {
reject(new Error("Request timed out."));
}
};
xhr.onerror = function() {
reject(new Error("Request failed."));
};
xhr.ontimeout = function() {
reject(new Error("Request timed out."));
};
});
}
Add your comment