this repo has no description
1import {NextResponse} from 'next/server';
2import {getUsers, getLatestPosts, Post} from '@/lib/atproto';
3
4let allPostsCache: Post[] = [];
5let lastFetchTime = 0;
6const CACHE_DURATION = 30 * 1000;
7
8export async function GET(request: Request) {
9 try {
10 const {searchParams} = new URL(request.url);
11 const offset = parseInt(searchParams.get('offset') || '0');
12 const limit = parseInt(searchParams.get('limit') || '50');
13 const now = Date.now();
14 if (allPostsCache.length === 0 || now - lastFetchTime > CACHE_DURATION) {
15 console.log('Fetching all posts from all users...');
16 const users = await getUsers();
17 const postsPromises = users.map(async user => {
18 return await getLatestPosts(user, 999);
19 });
20
21 const postsArrays = await Promise.all(postsPromises);
22
23 allPostsCache = postsArrays
24 .flatMap(p => p.posts)
25 .sort((a, b) => {
26 return new Date(b.record.createdAt).getTime() - new Date(a.record.createdAt).getTime();
27 });
28
29 lastFetchTime = now;
30 console.log(`Cached ${allPostsCache.length} total posts from ${users.length} users`);
31 }
32 const batch = allPostsCache.slice(offset, offset + limit);
33 const hasMore = offset + limit < allPostsCache.length;
34
35 return NextResponse.json({
36 posts: batch,
37 hasMore,
38 total: allPostsCache.length,
39 offset: offset + batch.length,
40 });
41 } catch (error) {
42 console.error('Error fetching posts:', error);
43 return NextResponse.json(
44 {posts: [], hasMore: false, total: 0, error: 'Failed to fetch posts'},
45 {status: 500}
46 );
47 }
48}