NeahFront9/app/api/news/route.ts
2025-04-14 19:27:52 +02:00

89 lines
2.7 KiB
TypeScript

import { NextResponse } from 'next/server';
// FastAPI server configuration
const API_HOST = process.env.API_HOST || 'http://172.16.0.104:8000';
// Helper function to clean HTML content
function cleanHtmlContent(content: string): string {
if (!content) return '';
// Remove HTML tags
return content
.replace(/<[^>]*>/g, '')
.replace(/&nbsp;/g, ' ')
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.trim();
}
// Helper function to format time
function formatDateTime(dateStr: string): string {
const date = new Date(dateStr);
return date.toLocaleString('fr-FR', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false
}).replace(',', ' à'); // Format: "17 avr. à 15:30"
}
// Helper function to truncate text
function truncateText(text: string, maxLength: number): string {
if (!text || text.length <= maxLength) return text;
return text.substring(0, maxLength).trim() + '...';
}
export async function GET() {
try {
console.log(`Fetching news from FastAPI server at ${API_HOST}...`);
const response = await fetch(`${API_HOST}/news?limit=10`, { // Increased limit to 10 articles
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
cache: 'no-store',
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
}
const rawNews = await response.json();
// Format and clean the news data
const formattedNews = rawNews.map((article: any) => ({
...article,
title: truncateText(cleanHtmlContent(article.title), 100),
description: truncateText(cleanHtmlContent(article.description), 150),
formattedDate: formatDateTime(article.date),
source: article.source?.toLowerCase() || 'unknown',
category: article.category?.toUpperCase() || 'GENERAL',
url: article.url || '#',
}));
console.log(`Successfully fetched and formatted ${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',
details: error instanceof Error ? error.message : 'Unknown error',
server: API_HOST,
timestamp: new Date().toISOString(),
},
{ status: 500 }
);
}
}