news widget design 10

This commit is contained in:
alma 2025-04-15 11:50:58 +02:00
parent e9f19adb8c
commit 91959ffcc6

View File

@ -1,7 +1,15 @@
import { NextResponse } from 'next/server';
import { Pool } from 'pg';
// FastAPI server configuration
const API_HOST = process.env.API_HOST || 'http://172.16.0.104:8000';
// PostgreSQL connection configuration
const pool = new Pool({
host: '172.16.0.104',
port: 5432,
database: 'rivacube',
user: 'alma',
connectionTimeoutMillis: 5000,
query_timeout: 5000
});
// Helper function to clean HTML content
function cleanHtmlContent(content: string): string {
@ -74,32 +82,21 @@ function formatSource(source: string): string {
}
export async function GET() {
let client;
try {
console.log(`Fetching news from FastAPI server at ${API_HOST}...`);
const response = await fetch(`${API_HOST}/news?limit=10`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
cache: 'no-store',
});
client = await pool.connect();
console.log('Connected to PostgreSQL database');
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
}
const result = await client.query(
'SELECT * FROM news ORDER BY date DESC LIMIT 5'
);
const rawNews = await response.json();
// Format and clean the news data
const formattedNews = rawNews.map((article: any) => {
const formattedNews = result.rows.map(article => {
const { displayDate, timestamp } = formatDateTime(article.date);
return {
id: article.id,
title: truncateText(cleanHtmlContent(article.title), 100),
description: truncateText(cleanHtmlContent(article.description), 150),
title: truncateText(article.title, 70),
description: truncateText(article.description, 100),
displayDate,
timestamp,
source: formatSource(article.source),
@ -108,25 +105,27 @@ export async function GET() {
};
});
console.log(`Successfully fetched and formatted ${formattedNews.length} news articles`);
console.log(`Successfully fetched ${formattedNews.length} news articles`);
return NextResponse.json(formattedNews);
} catch (error) {
console.error('Error in news API:', {
error: error instanceof Error ? error.message : 'Unknown error',
apiHost: API_HOST,
stack: error instanceof Error ? error.stack : undefined,
timestamp: new Date().toISOString(),
});
return NextResponse.json(
{
error: 'Failed to fetch news',
error: 'Failed to fetch news',
details: error instanceof Error ? error.message : 'Unknown error',
server: API_HOST,
timestamp: new Date().toISOString(),
},
{ status: 500 }
);
} finally {
if (client) {
client.release();
}
}
}