feat(api): 接入 yahoo-finance2 构建股票自动行情引擎,并实装一键同步按钮
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
'use server';
|
||||
|
||||
import yahooFinance from 'yahoo-finance2';
|
||||
import { db } from '@/db';
|
||||
import { assets } from '@/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
|
||||
export async function syncAllStockPrices() {
|
||||
const stockAssets = await db
|
||||
.select()
|
||||
.from(assets)
|
||||
.where(eq(assets.type, 'STOCK'));
|
||||
|
||||
let successCount = 0;
|
||||
|
||||
for (const asset of stockAssets) {
|
||||
try {
|
||||
const quote = await yahooFinance.quote(asset.symbol);
|
||||
if (quote && quote.regularMarketPrice !== undefined) {
|
||||
await db
|
||||
.update(assets)
|
||||
.set({ latestPrice: quote.regularMarketPrice.toString() })
|
||||
.where(eq(assets.id, asset.id));
|
||||
successCount++;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch price for ${asset.symbol}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath('/dashboard');
|
||||
revalidatePath('/dashboard/assets');
|
||||
|
||||
return { success: true, count: successCount };
|
||||
}
|
||||
Reference in New Issue
Block a user