File size: 2,137 Bytes
062a991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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);
  }
}