File size: 1,581 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
import { and, eq } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { getDb } from "@/db";
import { notifications, postLikes, posts } from "@/db/schema";
import { ApiError, apiResponseError, readJsonObject, requireSameOrigin, requireUser } from "@/lib/api";

const likeSchema = z.object({ postId: z.string().uuid() });

export async function POST(request: NextRequest) {
  try {
    requireSameOrigin(request);
    const user = await requireUser(request);
    const payload = likeSchema.parse(await readJsonObject(request));
    const db = getDb();
    const [post] = await db.select().from(posts).where(eq(posts.id, payload.postId)).limit(1);
    if (!post) throw new ApiError(404, "Post not found.", "not_found");
    const [existing] = await db.select().from(postLikes).where(and(eq(postLikes.postId, payload.postId), eq(postLikes.userId, user.id))).limit(1);
    if (existing) {
      await db.delete(postLikes).where(and(eq(postLikes.postId, payload.postId), eq(postLikes.userId, user.id)));
      return NextResponse.json({ liked: false });
    }
    await db.insert(postLikes).values({ postId: payload.postId, userId: user.id }).onConflictDoNothing();
    if (post.authorId !== user.id) {
      await db.insert(notifications).values({
        userId: post.authorId,
        actorId: user.id,
        type: "post_like",
        title: `${user.name} liked your post`,
        href: "/feed",
      });
    }
    return NextResponse.json({ liked: true });
  } catch (error) {
    return apiResponseError(error);
  }
}