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); } }