7.1 게시글 CRUD API 및 페이지 연동 o

This commit is contained in:
koreacomp5
2025-10-09 16:49:06 +09:00
parent f6dc33a42c
commit 7342c9bea2
7 changed files with 136 additions and 2 deletions

View File

@@ -1,5 +1,8 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import prisma from "@/lib/prisma"; 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 }> }) { export async function GET(_: Request, context: { params: Promise<{ id: string }> }) {
const { id } = await context.params; const { id } = await context.params;
@@ -13,4 +16,28 @@ export async function GET(_: Request, context: { params: Promise<{ id: string }>
return NextResponse.json({ post }); 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);
await requirePermission({ userId, resource: "POST", action: "UPDATE" });
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);
await requirePermission({ userId, resource: "POST", action: "DELETE" });
const post = await prisma.post.update({ where: { id }, data: { status: "deleted" } });
return NextResponse.json({ post });
}

View File

@@ -48,6 +48,7 @@ export async function GET(req: Request) {
} }
const { page, pageSize, boardId, q, sort = "recent" } = parsed.data; const { page, pageSize, boardId, q, sort = "recent" } = parsed.data;
const where = { const where = {
NOT: { status: "deleted" as const },
...(boardId ? { boardId } : {}), ...(boardId ? { boardId } : {}),
...(q ...(q
? { ? {

View File

@@ -55,7 +55,7 @@ export function PostList({ boardId, sort = "recent", q }: { boardId?: string; so
{items.map((p) => ( {items.map((p) => (
<li key={p.id} style={{ padding: 12, border: "1px solid #eee", borderRadius: 8 }}> <li key={p.id} style={{ padding: 12, border: "1px solid #eee", borderRadius: 8 }}>
<div style={{ display: "flex", justifyContent: "space-between" }}> <div style={{ display: "flex", justifyContent: "space-between" }}>
<strong>{p.title}</strong> <strong><a href={`/posts/${p.id}`}>{p.title}</a></strong>
<span style={{ opacity: 0.7 }}>{new Date(p.createdAt).toLocaleString()}</span> <span style={{ opacity: 0.7 }}>{new Date(p.createdAt).toLocaleString()}</span>
</div> </div>
<div style={{ fontSize: 12, opacity: 0.8 }}> <div style={{ fontSize: 12, opacity: 0.8 }}>

View File

@@ -0,0 +1,51 @@
"use client";
import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { useToast } from "@/app/components/ui/ToastProvider";
export default function EditPostPage() {
const params = useParams<{ id: string }>();
const id = params?.id as string;
const router = useRouter();
const { show } = useToast();
const [form, setForm] = useState<{ title: string; content: string } | null>(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
(async () => {
const r = await fetch(`/api/posts/${id}`);
if (!r.ok) return;
const { post } = await r.json();
setForm({ title: post.title, content: post.content });
})();
}, [id]);
async function submit() {
if (!form) return;
try {
setLoading(true);
const r = await fetch(`/api/posts/${id}`, {
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify(form),
});
const data = await r.json();
if (!r.ok) throw new Error(JSON.stringify(data));
show("수정되었습니다");
router.push(`/posts/${id}`);
} catch (e) {
show("수정 실패");
} finally {
setLoading(false);
}
}
if (!form) return <div> ...</div>;
return (
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
<h1> </h1>
<input placeholder="제목" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
<textarea placeholder="내용" value={form.content} onChange={(e) => setForm({ ...form, content: e.target.value })} rows={10} />
<button disabled={loading} onClick={submit}>{loading ? "저장 중..." : "저장"}</button>
</div>
);
}

View File

@@ -0,0 +1,15 @@
import { notFound } from "next/navigation";
export default async function PostDetail({ params }: { params: { id: string } }) {
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL ?? ""}/api/posts/${params.id}`, { cache: "no-store" });
if (!res.ok) return notFound();
const { post } = await res.json();
return (
<div>
<h1>{post.title}</h1>
<p style={{ whiteSpace: "pre-wrap" }}>{post.content}</p>
</div>
);
}

View File

@@ -0,0 +1,40 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useToast } from "@/app/components/ui/ToastProvider";
export default function NewPostPage() {
const router = useRouter();
const { show } = useToast();
const [form, setForm] = useState({ boardId: "", title: "", content: "" });
const [loading, setLoading] = useState(false);
async function submit() {
try {
setLoading(true);
const r = await fetch("/api/posts", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ ...form }),
});
const data = await r.json();
if (!r.ok) throw new Error(JSON.stringify(data));
show("작성되었습니다");
router.push(`/posts/${data.post.id}`);
} catch (e) {
show("작성 실패");
} finally {
setLoading(false);
}
}
return (
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
<h1> </h1>
<input placeholder="boardId" value={form.boardId} onChange={(e) => setForm({ ...form, boardId: e.target.value })} />
<input placeholder="제목" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
<textarea placeholder="내용" value={form.content} onChange={(e) => setForm({ ...form, content: e.target.value })} rows={10} />
<button disabled={loading} onClick={submit}>{loading ? "저장 중..." : "등록"}</button>
</div>
);
}

View File

@@ -40,7 +40,7 @@
6.5 개인화 위젯(최근 본 글/알림 요약) o 6.5 개인화 위젯(최근 본 글/알림 요약) o
[게시판/컨텐츠] [게시판/컨텐츠]
7.1 게시글 CRUD API 및 페이지 연동 7.1 게시글 CRUD API 및 페이지 연동 o
7.2 목록 페이징/정렬/검색(제목/태그/작성자/기간) 7.2 목록 페이징/정렬/검색(제목/태그/작성자/기간)
7.3 태그/카테고리 모델 및 UI 7.3 태그/카테고리 모델 및 UI
7.4 첨부 업로드 및 본문 삽입 7.4 첨부 업로드 및 본문 삽입