72 lines
2.3 KiB
TypeScript
72 lines
2.3 KiB
TypeScript
import type { IServiceContainer } from '@stock-bot/services';
|
|
import { IB_CONFIG, getIbProxyUrl } from '../shared/config';
|
|
import { fetchSession } from './fetch-session.action';
|
|
|
|
export async function fetchExchanges(services: IServiceContainer): Promise<unknown[] | null> {
|
|
try {
|
|
// First get session headers
|
|
const sessionHeaders = await fetchSession(services);
|
|
if (!sessionHeaders) {
|
|
throw new Error('Failed to get session headers');
|
|
}
|
|
|
|
services.logger.info('🔍 Fetching exchanges with session headers...');
|
|
|
|
// The URL for the exchange data API
|
|
const exchangeUrl = IB_CONFIG.BASE_URL + IB_CONFIG.EXCHANGE_API;
|
|
|
|
// Prepare headers - include all session headers plus any additional ones
|
|
const requestHeaders = {
|
|
...sessionHeaders,
|
|
Accept: 'application/json, text/plain, */*',
|
|
'Accept-Language': 'en-US,en;q=0.9',
|
|
'Cache-Control': 'no-cache',
|
|
Pragma: 'no-cache',
|
|
'Sec-Fetch-Dest': 'empty',
|
|
'Sec-Fetch-Mode': 'cors',
|
|
'Sec-Fetch-Site': 'same-origin',
|
|
'X-Requested-With': 'XMLHttpRequest',
|
|
};
|
|
|
|
services.logger.info('📤 Making request to exchange API...', {
|
|
url: exchangeUrl,
|
|
headerCount: Object.keys(requestHeaders).length,
|
|
});
|
|
|
|
const proxy = getIbProxyUrl();
|
|
|
|
// Use fetch with optional proxy configuration
|
|
const response = await fetch(exchangeUrl, {
|
|
method: 'GET',
|
|
headers: requestHeaders,
|
|
...(proxy ? { proxy } : {}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
services.logger.error('❌ Exchange API request failed', {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const data = await response.json();
|
|
const exchanges = data?.exchanges || [];
|
|
services.logger.info('✅ Exchange data fetched successfully');
|
|
|
|
if (services.mongodb) {
|
|
services.logger.info('Saving IB exchanges to MongoDB...');
|
|
await services.mongodb.batchUpsert('ibExchanges', exchanges, ['id', 'country_code']);
|
|
services.logger.info('✅ Exchange IB data saved to MongoDB:', {
|
|
count: exchanges.length,
|
|
});
|
|
} else {
|
|
services.logger.warn('MongoDB service not available, skipping data persistence');
|
|
}
|
|
|
|
return exchanges;
|
|
} catch (error) {
|
|
services.logger.error('❌ Failed to fetch exchanges', { error });
|
|
return null;
|
|
}
|
|
}
|