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

const commentSchema = z.object({
  postId: z.string().uuid(),
  content: z.string().trim().min(1).max(1200),
});

export async function POST(request: NextRequest) {
  try {
    requireSameOrigin(request);
    const user = await requireUser(request);
    const payload = commentSchema.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 [comment] = await db.insert(comments).values({ postId: post.id, authorId: user.id, content: payload.content }).returning();
    if (post.authorId !== user.id) {
      await db.insert(notifications).values({
        userId: post.authorId,
        actorId: user.id,
        type: "comment",
        title: `${user.name} commented on your post`,
        body: payload.content.slice(0, 160),
        href: "/feed",
      });
    }
    await writeAuditLog({ actorId: user.id, action: "comment.created", entityType: "comment", entityId: comment.id });
    return NextResponse.json({ comment }, { status: 201 });
  } catch (error) {
    return apiResponseError(error);
  }
}