SoftTraderFrontend/lib/newsApi.ts
2026-03-20 11:10:13 -04:00

72 lines
1.9 KiB
TypeScript

const API_BASE = 'https://api.dongfeng-systems.org'
export interface NewsItem {
title: string
publisher: string
score: number
publishedAt: string
url: string
}
/**
* Fetch news items for a given keyword
* @param keyword - Symbol or topic to search for
* @param requestAmount - Number of items to request (default: 10)
* @returns Array of news items sorted by publishedAt (newest first)
*/
export async function getNewsFeed(
keyword: string,
user: string = 'frontend',
requestAmount: number = 10
): Promise<NewsItem[]> {
const encodedKeyword = encodeURIComponent(keyword)
const res = await fetch(
`${API_BASE}/api/news-sentiment/feed?user=${encodeURIComponent(user)}&keyword=${encodedKeyword}&request-amount=${requestAmount}`,
{ cache: 'no-store' }
)
if (!res.ok) {
throw new Error(`Failed to fetch news for "${keyword}"`)
}
const items: NewsItem[] = await res.json()
// Sort by publishedAt descending (newest first)
return items.sort((a, b) => {
const dateA = new Date(a.publishedAt).getTime()
const dateB = new Date(b.publishedAt).getTime()
return dateB - dateA
})
}
/**
* Trigger a server-side refresh of the news sentiment cache.
* @returns true if the server refreshed successfully, false otherwise
*/
export async function refreshNewsFeed(user: string = 'frontend'): Promise<boolean> {
const res = await fetch(
`${API_BASE}/api/news-sentiment/refresh?user=${encodeURIComponent(user)}`,
{ cache: 'no-store' }
)
if (!res.ok) return false
const result = await res.json()
// API returns a boolean directly
return result === true || result?.success === true
}
export function formatPublishedDate(isoDateString: string): string {
try {
const date = new Date(isoDateString)
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
} catch {
return isoDateString
}
}