import {NextResponse} from 'next/server'; import {getUsers, getLatestPosts, Post} from '@/lib/atproto'; let allPostsCache: Post[] = []; let lastFetchTime = 0; const CACHE_DURATION = 30 * 1000; export async function GET(request: Request) { try { const {searchParams} = new URL(request.url); const offset = parseInt(searchParams.get('offset') || '0'); const limit = parseInt(searchParams.get('limit') || '50'); const now = Date.now(); if (allPostsCache.length === 0 || now - lastFetchTime > CACHE_DURATION) { console.log('Fetching all posts from all users...'); const users = await getUsers(); const postsPromises = users.map(async user => { return await getLatestPosts(user, 999); }); const postsArrays = await Promise.all(postsPromises); allPostsCache = postsArrays .flatMap(p => p.posts) .sort((a, b) => { return new Date(b.record.createdAt).getTime() - new Date(a.record.createdAt).getTime(); }); lastFetchTime = now; console.log(`Cached ${allPostsCache.length} total posts from ${users.length} users`); } const batch = allPostsCache.slice(offset, offset + limit); const hasMore = offset + limit < allPostsCache.length; return NextResponse.json({ posts: batch, hasMore, total: allPostsCache.length, offset: offset + batch.length, }); } catch (error) { console.error('Error fetching posts:', error); return NextResponse.json( {posts: [], hasMore: false, total: 0, error: 'Failed to fetch posts'}, {status: 500} ); } }