const fs = require('fs');
/**
* Aggregates values from multiple API endpoints based on a configuration file.
* @param {string} configPath Path to the configuration file.
* @returns {Promise<object>} A promise that resolves with the aggregated data.
* @throws {Error} If the configuration file is invalid or an API call fails.
*/
async function aggregateData(configPath) {
try {
const config = require(configPath); // Load configuration from file
const aggregatedData = {};
for (const endpointName in config.endpoints) {
if (config.endpoints.hasOwnProperty(endpointName)) {
const endpoint = config.endpoints[endpointName];
const apiUrl = endpoint.apiUrl;
const method = endpoint.method || 'GET'; // Default to GET
const params = endpoint.params || {};
try {
const response = await fetch(apiUrl, {
method: method,
headers: {
'Content-Type': 'application/json',
...endpoint.headers // Add any custom headers
},
body: JSON.stringify(params) // Convert params to JSON if needed
});
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// Aggregate data based on endpoint structure. Adapt as needed.
if (Array.isArray(data)) {
aggregatedData[endpointName] = data; //Store as an array
} else {
aggregatedData[endpointName] = data; //Store as object
}
} catch (error) {
console.error(`Error fetching data from ${apiUrl}:`, error);
throw error; // Re-throw the error to stop the process
}
}
}
return aggregatedData;
} catch (error) {
console.error("Error reading configuration:", error);
throw error;
}
}
module.exports = aggregateData;
Add your comment