diff --git a/app/api/news/purge-cache/route.ts b/app/api/news/purge-cache/route.ts new file mode 100644 index 00000000..d5261e06 --- /dev/null +++ b/app/api/news/purge-cache/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from 'next/server'; +import { invalidateNewsCache } from '@/lib/redis'; + +export async function POST() { + try { + await invalidateNewsCache(); + return NextResponse.json({ success: true }); + } catch (error) { + console.error('Failed to invalidate news cache:', error); + return NextResponse.json( + { error: 'Failed to invalidate cache', details: error instanceof Error ? error.message : 'Unknown error' }, + { status: 500 } + ); + } +} \ No newline at end of file diff --git a/app/api/news/route.ts b/app/api/news/route.ts index 44bb2ee3..d499f8ac 100644 --- a/app/api/news/route.ts +++ b/app/api/news/route.ts @@ -85,21 +85,29 @@ export async function GET(request: Request) { const url = new URL(request.url); const forceRefresh = url.searchParams.get('refresh') === 'true'; + // Get limit from query params or default to 100 + const limit = url.searchParams.get('limit') || '100'; + + // Also bypass cache if a non-default limit is explicitly requested + const bypassCache = forceRefresh || (url.searchParams.has('limit') && limit !== '100'); + + console.log(`News API request: limit=${limit}, forceRefresh=${forceRefresh}, bypassCache=${bypassCache}`); + // Try to get data from cache if not forcing refresh - if (!forceRefresh) { - const cachedNews = await getCachedNewsData(); + if (!bypassCache) { + const cachedNews = await getCachedNewsData(limit); if (cachedNews) { - console.log('Using cached news data'); + console.log(`Using cached news data (${cachedNews.length} articles)`); return NextResponse.json(cachedNews); } } - console.log('Fetching news from FastAPI server...'); + console.log(`Fetching news from FastAPI server with limit=${limit}...`); - // Get limit from query params or default to 100 - const limit = url.searchParams.get('limit') || '100'; + const apiUrl = `${env.NEWS_API_URL}/news?limit=${limit}`; + console.log(`Full API URL: ${apiUrl}`); - const response = await fetch(`${env.NEWS_API_URL}/news?limit=${limit}`, { + const response = await fetch(apiUrl, { method: 'GET', headers: { 'Accept': 'application/json', @@ -127,6 +135,7 @@ export async function GET(request: Request) { let articles; try { articles = await response.json(); + console.log(`News API returned ${articles.length} articles with limit=${limit}`); } catch (error) { console.error('Failed to parse news API response:', error); return NextResponse.json( @@ -146,8 +155,10 @@ export async function GET(request: Request) { url: article.url })); + console.log(`Formatted and returning ${formattedNews.length} news articles`); + // Cache the results - await cacheNewsData(formattedNews); + await cacheNewsData(formattedNews, limit); return NextResponse.json(formattedNews); } catch (error) { diff --git a/components/news.tsx b/components/news.tsx index fa2b6fd0..32403ee7 100644 --- a/components/news.tsx +++ b/components/news.tsx @@ -29,7 +29,7 @@ export function News() { if (!isRefresh) setLoading(true); try { - const response = await fetch(isRefresh ? '/api/news?refresh=true' : '/api/news'); + const response = await fetch(isRefresh ? '/api/news?refresh=true&limit=100' : '/api/news?limit=100'); if (!response.ok) { throw new Error('Failed to fetch news'); } @@ -37,11 +37,7 @@ export function News() { const data = await response.json(); // Debug log the date values - console.log('News data dates:', data.map((item: NewsItem) => ({ - id: item.id, - displayDate: item.displayDate, - timestamp: item.timestamp - }))); + console.log(`News component received ${data.length} articles`); setNews(data); setError(null); @@ -84,6 +80,9 @@ export function News() { Nouvelles + + ({news.length}) + + ); } @@ -152,6 +198,26 @@ export function ObservatoryView() { ({filteredNews.length} articles) +
+ + +
diff --git a/lib/redis.ts b/lib/redis.ts index 80bd3825..a26bb96a 100644 --- a/lib/redis.ts +++ b/lib/redis.ts @@ -130,7 +130,7 @@ export const KEYS = { `email:content:${userId}:${accountId}:${emailId}`, // New widget cache keys CALENDAR: (userId: string) => `widget:calendar:${userId}`, - NEWS: () => `widget:news`, // Global news cache, not user-specific + NEWS: (limit = '100') => `widget:news:${limit}`, // Include limit in cache key TASKS: (userId: string) => `widget:tasks:${userId}`, MESSAGES: (userId: string) => `widget:messages:${userId}` }; @@ -567,14 +567,15 @@ export async function invalidateCalendarCache( * Cache news data (global, not user-specific) */ export async function cacheNewsData( - data: any + data: any, + limit = '100' ): Promise { const redis = getRedisClient(); - const key = KEYS.NEWS(); + const key = KEYS.NEWS(limit); try { await redis.set(key, JSON.stringify(data), 'EX', TTL.NEWS); - console.log('News data cached successfully'); + console.log(`News data cached successfully (${data.length} articles, limit=${limit})`); } catch (error) { console.error('Error caching news data:', error); } @@ -583,9 +584,9 @@ export async function cacheNewsData( /** * Get cached news data */ -export async function getCachedNewsData(): Promise { +export async function getCachedNewsData(limit = '100'): Promise { const redis = getRedisClient(); - const key = KEYS.NEWS(); + const key = KEYS.NEWS(limit); try { const cachedData = await redis.get(key); @@ -593,7 +594,9 @@ export async function getCachedNewsData(): Promise { return null; } - return JSON.parse(cachedData); + const parsedData = JSON.parse(cachedData); + console.log(`Retrieved ${parsedData.length} articles from cache with limit=${limit}`); + return parsedData; } catch (error) { console.error('Error getting cached news data:', error); return null; @@ -603,13 +606,24 @@ export async function getCachedNewsData(): Promise { /** * Invalidate news cache */ -export async function invalidateNewsCache(): Promise { +export async function invalidateNewsCache(limit?: string): Promise { const redis = getRedisClient(); - const key = KEYS.NEWS(); try { - await redis.del(key); - console.log('News cache invalidated'); + if (limit) { + // Invalidate specific limit cache + const key = KEYS.NEWS(limit); + await redis.del(key); + console.log(`News cache invalidated for limit=${limit}`); + } else { + // Try to invalidate for some common limits + const limits = ['5', '50', '100', '200']; + for (const lim of limits) { + const key = KEYS.NEWS(lim); + await redis.del(key); + } + console.log('All news caches invalidated'); + } } catch (error) { console.error('Error invalidating news cache:', error); }