/**
* Merges datasets from multiple HTTP responses synchronously.
*
* @param {Array<object>} responses An array of HTTP response objects. Each object
* is expected to have a 'data' property containing the
* dataset (e.g., JSON string, array, etc.).
* @returns {object} A merged dataset. Returns an empty object if the input
* array is empty or invalid.
* @throws {Error} If any response data cannot be parsed.
*/
function mergeResponses(responses) {
if (!Array.isArray(responses) || responses.length === 0) {
return {}; // Return empty object for empty or invalid input
}
const mergedData = {};
for (const response of responses) {
if (typeof response !== 'object' || response === null || !response.hasOwnProperty('data')) {
console.warn("Invalid response object. Skipping."); // Log warning for invalid responses
continue;
}
try {
let data = response.data;
if (typeof data === 'string') {
data = JSON.parse(data); // Parse JSON string if necessary
}
if (Array.isArray(data)) {
mergedData = mergedData.concat(data); // Concatenate arrays
} else if (typeof data === 'object' && data !== null) {
// Merge objects. Handles cases where data is already an object.
for (const key in data) {
if (data.hasOwnProperty(key)) {
mergedData[key] = data[key];
}
}
} else {
console.warn("Unexpected data type:", typeof data, ". Skipping."); // Log warning for unexpected types
}
} catch (error) {
throw new Error("Error parsing response data: " + error.message);
}
}
return mergedData;
}
Add your comment