1. /**
  2. * Merges datasets from multiple HTTP responses synchronously.
  3. *
  4. * @param {Array<object>} responses An array of HTTP response objects. Each object
  5. * is expected to have a 'data' property containing the
  6. * dataset (e.g., JSON string, array, etc.).
  7. * @returns {object} A merged dataset. Returns an empty object if the input
  8. * array is empty or invalid.
  9. * @throws {Error} If any response data cannot be parsed.
  10. */
  11. function mergeResponses(responses) {
  12. if (!Array.isArray(responses) || responses.length === 0) {
  13. return {}; // Return empty object for empty or invalid input
  14. }
  15. const mergedData = {};
  16. for (const response of responses) {
  17. if (typeof response !== 'object' || response === null || !response.hasOwnProperty('data')) {
  18. console.warn("Invalid response object. Skipping."); // Log warning for invalid responses
  19. continue;
  20. }
  21. try {
  22. let data = response.data;
  23. if (typeof data === 'string') {
  24. data = JSON.parse(data); // Parse JSON string if necessary
  25. }
  26. if (Array.isArray(data)) {
  27. mergedData = mergedData.concat(data); // Concatenate arrays
  28. } else if (typeof data === 'object' && data !== null) {
  29. // Merge objects. Handles cases where data is already an object.
  30. for (const key in data) {
  31. if (data.hasOwnProperty(key)) {
  32. mergedData[key] = data[key];
  33. }
  34. }
  35. } else {
  36. console.warn("Unexpected data type:", typeof data, ". Skipping."); // Log warning for unexpected types
  37. }
  38. } catch (error) {
  39. throw new Error("Error parsing response data: " + error.message);
  40. }
  41. }
  42. return mergedData;
  43. }

Add your comment