59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
// Public REST API — post a comment on an article as the Bearer-authed user.
|
|
//
|
|
// POST /api/articles/:slug/comment — looks up the website_article by slug for
|
|
// its id, then inserts a website_article_comments row owned by the user behind
|
|
// the Authorization: Bearer token. Comment is required, non-empty, max 255
|
|
// chars (matches the VARCHAR(255) column). Fails soft — never returns a 500 for
|
|
// DB issues, just a generic error envelope.
|
|
|
|
import { apiError, apiJson } from "@/lib/api";
|
|
import { bearerUserId } from "@/lib/api-auth";
|
|
import { prisma } from "@/lib/prisma";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export async function POST(
|
|
req: Request,
|
|
{ params }: { params: Promise<{ slug: string }> },
|
|
) {
|
|
const uid = await bearerUserId(req);
|
|
if (!uid) return apiError("Unauthorized", 401);
|
|
|
|
const { slug } = await params;
|
|
|
|
const body = (await req.json().catch(() => ({}))) as { comment?: unknown };
|
|
const comment = typeof body.comment === "string" ? body.comment.trim() : "";
|
|
if (!comment) {
|
|
return apiError("Comment is required", 422);
|
|
}
|
|
if (comment.length > 255) {
|
|
return apiError("Comment may not be longer than 255 characters", 422);
|
|
}
|
|
|
|
try {
|
|
const article = await prisma.websiteArticles.findUnique({
|
|
where: { slug },
|
|
select: { id: true },
|
|
});
|
|
if (!article) {
|
|
return apiError("Article not found", 404);
|
|
}
|
|
|
|
const now = new Date();
|
|
await prisma.websiteArticleComments.create({
|
|
data: {
|
|
articleId: article.id,
|
|
userId: uid,
|
|
comment,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
|
|
return apiJson({ ok: true });
|
|
} catch {
|
|
return apiError("Could not post comment", 400);
|
|
}
|
|
}
|