import { after } from "next/server"; import { sendCommentPush } from "@/lib/comments/push"; import { getCommentViewer, listComments, requireCommentViewer } from "@/lib/comments/repository"; import { publishComment } from "@/lib/comments/publish"; import { errorResponse, HttpError, requireSameOrigin } from "@/lib/security/http"; import { limitRequest } from "@/lib/security/rate-limit"; export async function GET(request: Request) { try { const query = new URL(request.url).searchParams; const target = query.get("target"); if (!target) throw new HttpError(400, "target-required"); return Response.json(await listComments({ viewer: await getCommentViewer(), target, cursor: query.get("cursor"), sort: query.get("sort") ?? undefined }), { headers: { "Cache-Control": "private, no-store" } }); } catch (cause) { return errorResponse(cause); } } export async function POST(request: Request) { try { requireSameOrigin(request); const viewer = await requireCommentViewer(); await limitRequest("comment-publish", viewer.id, 20); const target = new URL(request.url).searchParams.get("target"); if (!target) throw new HttpError(400, "target-required"); const result = await publishComment(request, viewer, { target }); after(async () => { await sendCommentPush(result.id, result.version).catch(() => console.error("Comment notification failed")); }); return Response.json(result, { status: 201 }); } catch (cause) { return errorResponse(cause); } }