1. const fs = require('fs');
  2. /**
  3. * Aggregates values from multiple API endpoints based on a configuration file.
  4. * @param {string} configPath Path to the configuration file.
  5. * @returns {Promise<object>} A promise that resolves with the aggregated data.
  6. * @throws {Error} If the configuration file is invalid or an API call fails.
  7. */
  8. async function aggregateData(configPath) {
  9. try {
  10. const config = require(configPath); // Load configuration from file
  11. const aggregatedData = {};
  12. for (const endpointName in config.endpoints) {
  13. if (config.endpoints.hasOwnProperty(endpointName)) {
  14. const endpoint = config.endpoints[endpointName];
  15. const apiUrl = endpoint.apiUrl;
  16. const method = endpoint.method || 'GET'; // Default to GET
  17. const params = endpoint.params || {};
  18. try {
  19. const response = await fetch(apiUrl, {
  20. method: method,
  21. headers: {
  22. 'Content-Type': 'application/json',
  23. ...endpoint.headers // Add any custom headers
  24. },
  25. body: JSON.stringify(params) // Convert params to JSON if needed
  26. });
  27. if (!response.ok) {
  28. throw new Error(`API request failed with status ${response.status}: ${response.statusText}`);
  29. }
  30. const data = await response.json();
  31. // Aggregate data based on endpoint structure. Adapt as needed.
  32. if (Array.isArray(data)) {
  33. aggregatedData[endpointName] = data; //Store as an array
  34. } else {
  35. aggregatedData[endpointName] = data; //Store as object
  36. }
  37. } catch (error) {
  38. console.error(`Error fetching data from ${apiUrl}:`, error);
  39. throw error; // Re-throw the error to stop the process
  40. }
  41. }
  42. }
  43. return aggregatedData;
  44. } catch (error) {
  45. console.error("Error reading configuration:", error);
  46. throw error;
  47. }
  48. }
  49. module.exports = aggregateData;

Add your comment