Files
msgapp/src/app/api/posts/[id]/route.ts
2025-10-30 20:18:59 +09:00

52 lines
1.8 KiB
TypeScript

import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { z } from "zod";
import { getUserIdFromRequest } from "@/lib/auth";
import { requirePermission } from "@/lib/rbac";
export async function GET(_: Request, context: { params: Promise<{ id: string }> }) {
const { id } = await context.params;
const post = await prisma.post.findUnique({
where: { id },
include: {
board: { select: { id: true, name: true, slug: true } },
},
});
if (!post) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ post });
}
const updateSchema = z.object({
title: z.string().min(1).optional(),
content: z.string().min(1).optional(),
});
export async function PATCH(req: Request, context: { params: Promise<{ id: string }> }) {
const { id } = await context.params;
const userId = getUserIdFromRequest(req);
try {
await requirePermission({ userId, resource: "POST", action: "UPDATE" });
} catch (e) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await req.json();
const parsed = updateSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
const post = await prisma.post.update({ where: { id }, data: parsed.data });
return NextResponse.json({ post });
}
export async function DELETE(req: Request, context: { params: Promise<{ id: string }> }) {
const { id } = await context.params;
const userId = getUserIdFromRequest(req);
try {
await requirePermission({ userId, resource: "POST", action: "DELETE" });
} catch (e) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const post = await prisma.post.update({ where: { id }, data: { status: "deleted" } });
return NextResponse.json({ post });
}