index/functions/aggregateMultipleApiSources.md
aggregateMultipleApiSources<
T>(endpoints,aggregator,options?):Promise<T>
Fetch same data from multiple API endpoints and aggregate results
Useful for:
- Redundancy: Query multiple APIs and use the first successful response
- Fallback: Try primary API, then secondary, then tertiary
- Aggregation: Combine partial results from multiple sources
Type Parameters
| Type Parameter | Description |
|---|---|
T | Type of data returned from each endpoint |
Parameters
| Parameter | Type | Description |
|---|---|---|
endpoints | string[] | Array of API endpoints to query |
aggregator | (results) => T | Function to combine results from all endpoints |
options? | { fetcher?: (endpoint) => Promise<T>; logger?: Logger; } | Additional options (fetcher, logger) |
options.fetcher? | (endpoint) => Promise<T> | - |
options.logger? | Logger | - |
Returns
Promise<T>
Aggregated result from combining all endpoint responses
Examples
Fallback to secondary API
const price = await aggregateMultipleApiSources(
['https://api.primary.com/price', 'https://api.secondary.com/price'],
(results) => {
// Use first successful result
return results.find(r => r !== undefined) || { price: 0 };
},
{ fetcher: (url) => fetch(url).then(r => r.json()) }
);
Aggregate price from multiple exchanges
const avgPrice = await aggregateMultipleApiSources(
['exchange1.api/price', 'exchange2.api/price', 'exchange3.api/price'],
(results) => {
const prices = results.filter(r => typeof r === 'number') as number[];
if (prices.length === 0) return 0;
return prices.reduce((a, b) => a + b, 0) / prices.length;
}
);
Combine partial results from multiple sources
const combined = await aggregateMultipleApiSources(
[
'https://api1.com/liquidity',
'https://api2.com/liquidity',
'https://api3.com/liquidity'
],
(results) => ({
totalLiquidity: results.reduce((sum, r) => sum + (r?.tvl || 0), 0),
sources: results.filter(r => r !== undefined).length
})
);
Since
6.5.0 @adoption_gap Multi-source aggregation appears in 5+ locations with duplicate logic