AgPerry's picture
Add files using upload-large-folder tool
062a991 verified
Raw History Blame Contribute Delete
1.55 kB
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);
}
}