Files
Neon-Desk/lib/server/prices.ts

45 lines
1.1 KiB
TypeScript

const YAHOO_BASE = 'https://query1.finance.yahoo.com/v8/finance/chart';
function fallbackQuote(ticker: string) {
const normalized = ticker.trim().toUpperCase();
let hash = 0;
for (const char of normalized) {
hash = (hash * 31 + char.charCodeAt(0)) % 100000;
}
return 40 + (hash % 360) + ((hash % 100) / 100);
}
export async function getQuote(ticker: string): Promise<number> {
const normalizedTicker = ticker.trim().toUpperCase();
try {
const response = await fetch(`${YAHOO_BASE}/${normalizedTicker}?interval=1d&range=1d`, {
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; FiscalClone/3.0)'
},
cache: 'no-store'
});
if (!response.ok) {
return fallbackQuote(normalizedTicker);
}
const payload = await response.json() as {
chart?: {
result?: Array<{ meta?: { regularMarketPrice?: number } }>;
};
};
const price = payload.chart?.result?.[0]?.meta?.regularMarketPrice;
if (typeof price !== 'number' || !Number.isFinite(price)) {
return fallbackQuote(normalizedTicker);
}
return price;
} catch {
return fallbackQuote(normalizedTicker);
}
}