자바스크립트/Node JS

[Node JS] put - controller

KIMJAVAN 2024. 1. 19. 15:14
728x90
// gyController.deleteComment 함수 정의
// 이 함수는 비동기적으로 실행되며, req(request)와 res(response) 객체를 매개변수로 받습니다.
gyController.deleteComment = async(req, res) => {
    try {
        // 클라이언트에서 전송된 요청 본문(req.body)에서 삭제할 댓글의 ID 목록을 추출합니다.
        const deleteIdx = req.body.idxs;

        // 추출된 ID 목록을 콘솔에 로그로 출력합니다.
        console.log(deleteIdx);

        // 삭제할 댓글 ID가 없는 경우 (목록의 길이가 0인 경우),
        // HTTP 상태 코드 400과 함께 오류 메시지를 클라이언트에 전송합니다.
        if(deleteIdx.length === 0){
            return res.status(400).json({error : '삭제할 댓글이 없습니다'});
        }
        
        // 삭제할 댓글 ID 목록을 순회합니다.
        for(const idx of deleteIdx){
            // 각 댓글 ID에 대해 gyModel.deleteComment 함수를 호출하여 댓글을 삭제합니다.
            const deleteComment = await gyModel.deleteComment(idx);

            // 만약 댓글 삭제가 실패했다면 (deleteComment가 false 또는 null인 경우),
            // HTTP 상태 코드 503과 함께 오류 메시지를 클라이언트에 전송합니다.
            if(!deleteComment){
                return res.status(503).json ({error : `${idx}번 댓글 삭제 실패`});
            }
        }

        // 모든 댓글 삭제가 성공적으로 이루어졌다면,
        // HTTP 상태 코드 200과 함께 성공 메시지를 클라이언트에 전송합니다.
        return res.status(200).json({ message: '댓글이 성공적으로 삭제되었습니다.' });
    } catch(error) {
        // 처리 중에 예외가 발생한 경우,
        // 콘솔에 오류 로그를 출력하고, HTTP 상태 코드 500과 함께 오류 메시지를 클라이언트에 전송합니다.
        console.error("Error delete comment", error);
        return res.status(500).json({error : "Failed to delete comment"});
    }
}