Files
Mebbling/app/api/comments/route.ts
T

18 lines
1.0 KiB
TypeScript

import { NextResponse } from "next/server";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { externalUrl } from "@/lib/http";
import { notify } from "@/lib/notifications";
export async function POST(req: Request) {
try {
const user = await requireUser(); const form = await req.formData(); const postId = Number(form.get("postId")); const content = String(form.get("content") || "").trim();
if (!postId || !content || content.length > 5000) throw new Error("Invalid comment");
const post = db.prepare("SELECT author_id FROM posts WHERE id=? AND hidden=0").get(postId) as { author_id: number } | undefined;
if (!post) throw new Error("Post not found");
db.prepare("INSERT INTO comments(post_id,author_id,content) VALUES(?,?,?)").run(postId, user.id, content);
notify(post.author_id, user.id, postId, "comment", `@${user.username} 留言了你的貼文`);
return NextResponse.redirect(externalUrl(req, `/posts/${postId}`));
} catch { return NextResponse.redirect(externalUrl(req, "/")); }
}