91 lines
3.2 KiB
TypeScript
91 lines
3.2 KiB
TypeScript
// Example usage of the @stock-bot/http-client library
|
|
|
|
import { BunHttpClient } from '../src';
|
|
|
|
async function main() {
|
|
// Create a client instance
|
|
const client = new BunHttpClient({
|
|
baseURL: 'https://api.polygon.io',
|
|
timeout: 10000,
|
|
retries: 2,
|
|
retryDelay: 500,
|
|
headers: {
|
|
'X-API-Key': process.env.POLYGON_API_KEY || 'demo'
|
|
}
|
|
});
|
|
|
|
// Add event listeners for monitoring
|
|
client.on('response', ({host, response}) => {
|
|
console.log(`📦 Response from ${host}: ${response.status} (${response.timing.duration.toFixed(2)}ms)`);
|
|
});
|
|
|
|
client.on('error', ({host, error}) => {
|
|
console.error(`❌ Error from ${host}: ${error.message}`);
|
|
});
|
|
|
|
client.on('retryAttempt', ({attempt, config, delay}) => {
|
|
console.warn(`⚠️ Retry ${attempt}/${config.retries} for ${config.url} in ${delay}ms`);
|
|
});
|
|
|
|
try {
|
|
console.log('Fetching market data...');
|
|
|
|
// Make a GET request
|
|
const tickerResponse = await client.get('/v3/reference/tickers', {
|
|
headers: {
|
|
'Accept': 'application/json'
|
|
}
|
|
});
|
|
|
|
console.log(`Found ${tickerResponse.data.results.length} tickers`);
|
|
console.log(`First ticker: ${JSON.stringify(tickerResponse.data.results[0], null, 2)}`);
|
|
|
|
// Make a request that will fail
|
|
try {
|
|
await client.get('/non-existent-endpoint');
|
|
} catch (error) {
|
|
console.log('Expected error caught:', error.message);
|
|
}
|
|
|
|
// Multiple parallel requests
|
|
console.log('Making parallel requests...');
|
|
const [aaplData, msftData, amznData] = await Promise.all([
|
|
client.get('/v2/aggs/ticker/AAPL/range/1/day/2023-01-01/2023-01-15'),
|
|
client.get('/v2/aggs/ticker/MSFT/range/1/day/2023-01-01/2023-01-15'),
|
|
client.get('/v2/aggs/ticker/AMZN/range/1/day/2023-01-01/2023-01-15')
|
|
]);
|
|
|
|
console.log('Parallel requests completed:');
|
|
console.log(`- AAPL: ${aaplData.status}, data points: ${aaplData.data.results?.length || 0}`);
|
|
console.log(`- MSFT: ${msftData.status}, data points: ${msftData.data.results?.length || 0}`);
|
|
console.log(`- AMZN: ${amznData.status}, data points: ${amznData.data.results?.length || 0}`);
|
|
|
|
// Get client statistics
|
|
const stats = client.getStats();
|
|
console.log('\nClient Stats:');
|
|
console.log(`- Active connections: ${stats.activeConnections}`);
|
|
console.log(`- Total connections: ${stats.totalConnections}`);
|
|
console.log(`- Successful requests: ${stats.successfulRequests}`);
|
|
console.log(`- Failed requests: ${stats.failedRequests}`);
|
|
console.log(`- Average response time: ${stats.averageResponseTime.toFixed(2)}ms`);
|
|
console.log(`- Requests per second: ${stats.requestsPerSecond.toFixed(2)}`);
|
|
|
|
// Health check
|
|
const health = await client.healthCheck();
|
|
console.log(`\nClient health: ${health.healthy ? 'HEALTHY' : 'DEGRADED'}`);
|
|
console.log(`Health details: ${JSON.stringify(health.details, null, 2)}`);
|
|
|
|
} catch (error) {
|
|
console.error('Error in example:', error);
|
|
} finally {
|
|
// Always close the client when done to clean up resources
|
|
await client.close();
|
|
console.log('HTTP client closed');
|
|
}
|
|
}
|
|
|
|
// Run the example
|
|
main().catch(err => {
|
|
console.error('Example failed:', err);
|
|
process.exit(1);
|
|
});
|