BREAKING CHANGE(stocks): Unify stock provider API to discriminated IStockDataRequest and add company name/fullname enrichment
This commit is contained in:
@@ -2,8 +2,6 @@ import * as plugins from '../plugins.js';
|
||||
import type { IStockProvider, IProviderConfig, IProviderRegistry } from './interfaces/provider.js';
|
||||
import type {
|
||||
IStockPrice,
|
||||
IStockQuoteRequest,
|
||||
IStockBatchQuoteRequest,
|
||||
IStockPriceError,
|
||||
IStockDataRequest,
|
||||
IStockCurrentRequest,
|
||||
@@ -13,6 +11,15 @@ import type {
|
||||
TIntervalType
|
||||
} from './interfaces/stockprice.js';
|
||||
|
||||
// Simple request interfaces for convenience methods
|
||||
interface ISimpleQuoteRequest {
|
||||
ticker: string;
|
||||
}
|
||||
|
||||
interface ISimpleBatchRequest {
|
||||
tickers: string[];
|
||||
}
|
||||
|
||||
interface IProviderEntry {
|
||||
provider: IStockProvider;
|
||||
config: IProviderConfig;
|
||||
@@ -122,132 +129,26 @@ export class StockPriceService implements IProviderRegistry {
|
||||
.map(entry => entry.provider);
|
||||
}
|
||||
|
||||
public async getPrice(request: IStockQuoteRequest): Promise<IStockPrice> {
|
||||
const cacheKey = this.getCacheKey(request);
|
||||
const cached = this.getFromCache(cacheKey) as IStockPrice | null;
|
||||
|
||||
if (cached) {
|
||||
console.log(`Cache hit for ${request.ticker}`);
|
||||
return cached;
|
||||
}
|
||||
|
||||
const providers = this.getEnabledProviders();
|
||||
if (providers.length === 0) {
|
||||
throw new Error('No stock price providers available');
|
||||
}
|
||||
|
||||
let lastError: Error | undefined;
|
||||
|
||||
for (const provider of providers) {
|
||||
const entry = this.providers.get(provider.name)!;
|
||||
|
||||
try {
|
||||
const price = await this.fetchWithRetry(
|
||||
() => provider.fetchPrice(request),
|
||||
entry.config
|
||||
);
|
||||
|
||||
entry.successCount++;
|
||||
|
||||
// Use smart TTL based on data type
|
||||
const ttl = this.getCacheTTL(price.dataType);
|
||||
this.addToCache(cacheKey, price, ttl);
|
||||
|
||||
console.log(`Successfully fetched ${request.ticker} from ${provider.name}`);
|
||||
return price;
|
||||
} catch (error) {
|
||||
entry.errorCount++;
|
||||
entry.lastError = error as Error;
|
||||
entry.lastErrorTime = new Date();
|
||||
lastError = error as Error;
|
||||
|
||||
console.warn(
|
||||
`Provider ${provider.name} failed for ${request.ticker}: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Failed to fetch price for ${request.ticker} from all providers. Last error: ${lastError?.message}`
|
||||
);
|
||||
/**
|
||||
* Convenience method: Get current price for a single ticker
|
||||
*/
|
||||
public async getPrice(request: ISimpleQuoteRequest): Promise<IStockPrice> {
|
||||
const result = await this.getData({
|
||||
type: 'current',
|
||||
ticker: request.ticker
|
||||
});
|
||||
return result as IStockPrice;
|
||||
}
|
||||
|
||||
public async getPrices(request: IStockBatchQuoteRequest): Promise<IStockPrice[]> {
|
||||
const cachedPrices: IStockPrice[] = [];
|
||||
const tickersToFetch: string[] = [];
|
||||
|
||||
// Check cache for each ticker
|
||||
for (const ticker of request.tickers) {
|
||||
const cacheKey = this.getCacheKey({ ticker, includeExtendedHours: request.includeExtendedHours });
|
||||
const cached = this.getFromCache(cacheKey) as IStockPrice | null;
|
||||
|
||||
if (cached) {
|
||||
cachedPrices.push(cached);
|
||||
} else {
|
||||
tickersToFetch.push(ticker);
|
||||
}
|
||||
}
|
||||
|
||||
if (tickersToFetch.length === 0) {
|
||||
console.log(`All ${request.tickers.length} tickers served from cache`);
|
||||
return cachedPrices;
|
||||
}
|
||||
|
||||
const providers = this.getEnabledProviders();
|
||||
if (providers.length === 0) {
|
||||
throw new Error('No stock price providers available');
|
||||
}
|
||||
|
||||
let lastError: Error | undefined;
|
||||
let fetchedPrices: IStockPrice[] = [];
|
||||
|
||||
for (const provider of providers) {
|
||||
const entry = this.providers.get(provider.name)!;
|
||||
|
||||
try {
|
||||
fetchedPrices = await this.fetchWithRetry(
|
||||
() => provider.fetchPrices({
|
||||
tickers: tickersToFetch,
|
||||
includeExtendedHours: request.includeExtendedHours
|
||||
}),
|
||||
entry.config
|
||||
);
|
||||
|
||||
entry.successCount++;
|
||||
|
||||
// Cache the fetched prices with smart TTL
|
||||
for (const price of fetchedPrices) {
|
||||
const cacheKey = this.getCacheKey({
|
||||
ticker: price.ticker,
|
||||
includeExtendedHours: request.includeExtendedHours
|
||||
});
|
||||
const ttl = this.getCacheTTL(price.dataType);
|
||||
this.addToCache(cacheKey, price, ttl);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Successfully fetched ${fetchedPrices.length} prices from ${provider.name}`
|
||||
);
|
||||
break;
|
||||
} catch (error) {
|
||||
entry.errorCount++;
|
||||
entry.lastError = error as Error;
|
||||
entry.lastErrorTime = new Date();
|
||||
lastError = error as Error;
|
||||
|
||||
console.warn(
|
||||
`Provider ${provider.name} failed for batch request: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (fetchedPrices.length === 0 && lastError) {
|
||||
throw new Error(
|
||||
`Failed to fetch prices from all providers. Last error: ${lastError.message}`
|
||||
);
|
||||
}
|
||||
|
||||
return [...cachedPrices, ...fetchedPrices];
|
||||
/**
|
||||
* Convenience method: Get current prices for multiple tickers
|
||||
*/
|
||||
public async getPrices(request: ISimpleBatchRequest): Promise<IStockPrice[]> {
|
||||
const result = await this.getData({
|
||||
type: 'batch',
|
||||
tickers: request.tickers
|
||||
});
|
||||
return result as IStockPrice[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -272,15 +173,9 @@ export class StockPriceService implements IProviderRegistry {
|
||||
for (const provider of providers) {
|
||||
const entry = this.providers.get(provider.name)!;
|
||||
|
||||
// Check if provider supports the new fetchData method
|
||||
if (typeof (provider as any).fetchData !== 'function') {
|
||||
console.warn(`Provider ${provider.name} does not support new API, skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.fetchWithRetry(
|
||||
() => (provider as any).fetchData(request),
|
||||
() => provider.fetchData(request),
|
||||
entry.config
|
||||
) as IStockPrice | IStockPrice[];
|
||||
|
||||
@@ -420,13 +315,6 @@ export class StockPriceService implements IProviderRegistry {
|
||||
throw lastError || new Error('Unknown error during fetch');
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy cache key generation
|
||||
*/
|
||||
private getCacheKey(request: IStockQuoteRequest): string {
|
||||
return `${request.ticker}:${request.includeExtendedHours || false}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* New cache key generation for discriminated union requests
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user