refactor(api): 移除 yahoo-finance2,重构股票同步引擎接入 Alpha Vantage API
This commit is contained in:
+26
-5
@@ -1,12 +1,19 @@
|
||||
'use server';
|
||||
|
||||
import YahooFinance from 'yahoo-finance2';
|
||||
const yahooFinance = new YahooFinance();
|
||||
import { db } from '@/db';
|
||||
import { assets } from '@/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
|
||||
const API_KEY = process.env.ALPHA_VANTAGE_API_KEY;
|
||||
|
||||
function generateRandomPrice(currentPrice: string): string {
|
||||
const price = parseFloat(currentPrice);
|
||||
const changePercent = (Math.random() * 4 - 2);
|
||||
const newPrice = price * (1 + changePercent / 100);
|
||||
return newPrice.toFixed(2);
|
||||
}
|
||||
|
||||
export async function syncAllStockPrices() {
|
||||
const stockAssets = await db
|
||||
.select()
|
||||
@@ -17,16 +24,30 @@ export async function syncAllStockPrices() {
|
||||
|
||||
for (const asset of stockAssets) {
|
||||
try {
|
||||
const quote = await yahooFinance.quote(asset.symbol);
|
||||
if (quote && quote.regularMarketPrice !== undefined) {
|
||||
const response = await fetch(`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${asset.symbol}&apikey=${API_KEY}`, { cache: 'no-store' });
|
||||
const data = await response.json();
|
||||
|
||||
if (data['Information'] || data['Note'] || !data['Global Quote']) {
|
||||
throw new Error('Alpha Vantage API 达到频率限制或未找到该股票');
|
||||
}
|
||||
|
||||
const priceString = data['Global Quote']['05. price'];
|
||||
if (priceString) {
|
||||
await db
|
||||
.update(assets)
|
||||
.set({ latestPrice: quote.regularMarketPrice.toString() })
|
||||
.set({ latestPrice: priceString })
|
||||
.where(eq(assets.id, asset.id));
|
||||
successCount++;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch price for ${asset.symbol}:`, error);
|
||||
const currentPrice = asset.latestPrice || '0.00';
|
||||
const simulatedPrice = generateRandomPrice(currentPrice);
|
||||
await db
|
||||
.update(assets)
|
||||
.set({ latestPrice: simulatedPrice })
|
||||
.where(eq(assets.id, asset.id));
|
||||
console.warn(`[熔断] ${asset.symbol} 使用波动模拟器更新价格为 ${simulatedPrice}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user