게시글 수정, 삭제 api

Byeonghyeon·2024년 12월 2일

PUT

수정 api도 작성이나 조회 api와 크게 다를 것은 없다.

export async function PUT(req: Request) {
    try {
        const body = await req.json();
        const requestUser = req.headers.get("requestUser");

        if (!requestUser) {
            return NextResponse.json({ error: "User is required" }, { status: 400 });
        }

         // 해당 포스트를 조회하여 posteduser 가져오기
        const post = await prisma.post.findUnique({
            where: { id: body.id },
        });

        // 포스트가 존재하지 않는 경우
        if (!post) {
            return NextResponse.json({ error: "Post not found" }, { status: 404 });
        }


        if (post.posteduser === requestUser) {
            const updatedPost = await prisma.post.update({
                where: { id: body.id },
                data: { title: body.title, content: body.content }
            });
            return NextResponse.json(updatedPost, { status: 200 });
        }
    } catch (err) {
        console.error(err);
        return NextResponse.json({ error: "Failed to update notice" }, { status: 500 });
    }
}

다만 수정을 요청한 유저가 작성자와 같아야 수정이 되어야 하므로 작성자와 수정을 요청한 유저가 같은지 검증하는 과정이 있으면 된다.

if (post.posteduser === requestUser) {
            const updatedPost = await prisma.post.update({
                where: { id: body.id },
                data: { title: body.title, content: body.content }
            });
            return NextResponse.json(updatedPost, { status: 200 });
        }

공지사항 같은 경우에는 관리자만 수정이 가능해야 하므로 관리자인지 아닌지 검증하는 isAdmin 메소드를 추가해주면 된다.

async function isAdmin(requestUser: string) {
    const user = await prisma.user.findUnique({
        where: { email: requestUser },
    });
    return user?.role === "admin";
}

DELETE

문제는 삭제인데, 공지사항 같은 경우는
1. 요청한 유저가 관리자이고
2. 작성자와 요청한 유저가 같은 사람이라면
삭제가 되도록 하면 되니 큰 문제는 없다.

문제는 게시글이다.

model Post {
  id         Int       @id @default(autoincrement())
  title      String
  content    String
  posteduser String
  createdAt  DateTime  @default(now())
  comments   Comment[] // Post에 연결된 Comment 목록을 참조
}

다시 Post 모델을 보자

Post에는 comments라는 속성이 있는데 해당 Post에 연결된 Comment(댓글)의 목록을 참조하는 속성이다.

Post를 그냥 삭제해버리면 Post에 연결된 댓글이 남아있는 문제가 발생한다.

그렇기 때문에 Post를 삭제하기 전에 필수적으로 Post에 연결된 Comment를 먼저 삭제해주는 과정이 필요하다.

export async function DELETE(req: Request) {
    try{
        const body = await req.json();
        const requestUser = req.headers.get("requestUser");

        if (!requestUser) {
            return NextResponse.json({ error: "User is required" }, { status: 400 });
        }

        const postId = parseInt(body.id);

        // 해당 포스트를 조회하여 posteduser 가져오기
        const post = await prisma.post.findUnique({
            where: { id: postId },
        });

        // 포스트가 존재하지 않는 경우
        if (!post) {
            return NextResponse.json({ error: "Post not found" }, { status: 404 });
        }


        if (post.posteduser === requestUser) {
            // 댓글 삭제
            await prisma.comment.deleteMany({
                where: {
                    postid: body.id,
                },
            });

            const deletedPost = await prisma.post.delete({
                where: {id: postId}
            });
            return NextResponse.json(deletedPost, { status: 200 });
        }
        else {
            return NextResponse.json({error: "You do not have permission to delete"}, { status: 400 })
        }
    } catch (err) {
        console.log(err);
        return NextResponse.json({ error: "Failed to delete post" }, { status: 500 });
    }
}

먼저 클라이언트로부터 삭제해야하는 Post의 id를 이용해 해당 Post에 연결된 댓글들을 삭제한다.

// 댓글 삭제
            await prisma.comment.deleteMany({
                where: {
                    postid: body.id,
                },
            });

그 후 Post를 삭제해주면 된다.

const deletedPost = await prisma.post.delete({
                where: {id: postId}
            });
            return NextResponse.json(deletedPost, { status: 200 });

0개의 댓글