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

20 lines
1.3 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";
const allowed = new Set(["👍", "❤️", "🎉", "🤔"]);
export async function POST(req: Request) {
try {
const user = await requireUser(); const form = await req.formData(); const postId = Number(form.get("postId")); const emoji = String(form.get("emoji"));
if (!postId || !allowed.has(emoji)) throw new Error("Invalid reaction");
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");
const found = db.prepare("SELECT 1 FROM reactions WHERE post_id=? AND user_id=? AND emoji=?").get(postId, user.id, emoji);
if (found) db.prepare("DELETE FROM reactions WHERE post_id=? AND user_id=? AND emoji=?").run(postId, user.id, emoji);
else { db.prepare("INSERT INTO reactions(post_id,user_id,emoji) VALUES(?,?,?)").run(postId, user.id, emoji); notify(post.author_id, user.id, postId, "reaction", `@${user.username} 對你的貼文給了 ${emoji}`); }
return NextResponse.redirect(externalUrl(req, `/posts/${postId}`));
} catch { return NextResponse.redirect(externalUrl(req, "/")); }
}