NeahFront9/app/api/news/route.ts
2025-04-15 12:23:58 +02:00

109 lines
3.1 KiB
TypeScript

import { NextResponse } from 'next/server';
// FastAPI server configuration
const API_URL = 'http://172.16.0.104:8000';
// Helper function to format time
function formatDateTime(dateStr: string): { displayDate: string, timestamp: string } {
try {
const date = new Date(dateStr);
const day = date.getDate();
const month = date.toLocaleString('fr-FR', { month: 'short' }).toLowerCase();
return {
displayDate: `${day} ${month}.`,
timestamp: date.toLocaleString('fr-FR', {
day: '2-digit',
month: 'short',
hour: '2-digit',
minute: '2-digit',
hour12: false
}).replace(',', ' à')
};
} catch (error) {
return { displayDate: 'N/A', timestamp: 'N/A' };
}
}
// Helper function to truncate text
function truncateText(text: string, maxLength: number): string {
if (!text || text.length <= maxLength) return text;
const lastSpace = text.lastIndexOf(' ', maxLength);
const truncated = text.substring(0, lastSpace > 0 ? lastSpace : maxLength).trim();
return truncated.replace(/[.,!?]$/, '') + '...';
}
// Helper function to format category
function formatCategory(category: string): string {
if (!category) return 'GENERAL';
const categoryMap: { [key: string]: string } = {
'GLOBAL ISSUES - WORLD AFFAIRS': 'WORLD',
'UN NEWS - GLOBAL NEWS': 'UN NEWS',
'GLOBAL NEWS': 'WORLD',
};
const normalizedCategory = category.toUpperCase();
return categoryMap[normalizedCategory] || normalizedCategory;
}
// Helper function to format source
function formatSource(source: string): string {
if (!source) return '';
const sourceName = source
.replace(/^(https?:\/\/)?(www\.)?/i, '')
.split('.')[0]
.toLowerCase()
.replace(/[^a-z0-9]/g, ' ')
.trim();
return sourceName.charAt(0).toUpperCase() + sourceName.slice(1);
}
export async function GET() {
try {
console.log('Fetching news from FastAPI server...');
const response = await fetch(`${API_URL}/news?limit=10`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const articles = await response.json();
const formattedNews = articles.map((article: any) => {
const { displayDate, timestamp } = formatDateTime(article.date);
return {
id: article.id,
title: truncateText(article.title, 70),
description: truncateText(article.description, 100),
displayDate,
timestamp,
source: formatSource(article.source),
category: formatCategory(article.category),
url: article.url || '#'
};
});
console.log(`Successfully fetched ${formattedNews.length} news articles`);
return NextResponse.json(formattedNews);
} catch (error) {
console.error('API error:', {
error: error instanceof Error ? error.message : 'Unknown error',
server: API_URL
});
return NextResponse.json(
{
error: 'Failed to fetch news',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}