import { and, count, desc, eq, inArray } from "drizzle-orm"; import { NextRequest, NextResponse } from "next/server"; import { getDb } from "@/db"; import { comments, postLikes, posts, users } from "@/db/schema"; import { apiResponseError, parseLimit } from "@/lib/api"; import { getSessionUser } from "@/lib/session"; export async function GET(request: NextRequest) { try { const limit = parseLimit(request.nextUrl.searchParams.get("limit"), 20, 50); const session = await getSessionUser(request); const db = getDb(); const rows = await db.select({ post: posts, author: { id: users.id, name: users.name, username: users.username, headline: users.headline, avatarUrl: users.avatarUrl, }, }) .from(posts) .innerJoin(users, eq(users.id, posts.authorId)) .orderBy(desc(posts.createdAt)) .limit(limit); const postIds = rows.map((row) => row.post.id); const likeRows = postIds.length ? await db.select({ postId: postLikes.postId, value: count() }).from(postLikes).where(inArray(postLikes.postId, postIds)).groupBy(postLikes.postId) : []; const commentRows = postIds.length ? await db.select({ postId: comments.postId, value: count() }).from(comments).where(inArray(comments.postId, postIds)).groupBy(comments.postId) : []; const myLikes = session && postIds.length ? await db.select({ postId: postLikes.postId }).from(postLikes).where(and(inArray(postLikes.postId, postIds), eq(postLikes.userId, session.user.id))) : []; const likeCount = new Map(likeRows.map((row) => [row.postId, row.value])); const commentCount = new Map(commentRows.map((row) => [row.postId, row.value])); const liked = new Set(myLikes.map((row) => row.postId)); return NextResponse.json({ posts: rows.map((row) => ({ ...row.post, author: row.author, likes: likeCount.get(row.post.id) ?? 0, comments: commentCount.get(row.post.id) ?? 0, liked: liked.has(row.post.id), })), }); } catch (error) { return apiResponseError(error); } }