댓글 API 등록하기

댓글 달기

1. 경로 설정

const API = "/api";
...
const ADD_COMMENT = "/:id/comment";
...
const routes = {
...,
  api: API,
  addComment: ADD_COMMENT
}

2. 라우터 등록

apiRouter.js

import express from "express";
import routes from "../routes";
import { postRegisterView, postAddComment  } from "../controllers/videoController";
const apiRouter = express.Router();

apiRouter.post(routes.addComment, postAddComment);

export default apiRouter;

3. 컨트롤러 연결

videoController.js

import routes from "../routes";
import Video from "../models/Video";
import Comment from "../models/Comment";
...
export const videoDetail = async (req,res) => {
    const {params:{id}} = req;
    try{
        const video = await Video.findById(id)
        .populate("creator")
        // 비디오 모델에서 comments 기능 사용 설정
        .populate("comments");
        ...
}

// comment 
export const postAddComment = async (req, res) => {
    const {
        params : { id },
        body : { comment },
        user
    } = req;
    //console.log(user) 
    try {
        const video = await Video.findById(id);
        const newComment = await Comment.create({
            text: comment,
            creator: user.id
        });
        video.comments.push(newComment.id);
        video.save();
    } catch (error) {
        console.log(error)
        res.status(400);
    } finally {
        res.end();
    }
}

4. 프론트단 addComment.js 작성

// axios 연결
import axios from "axios";
const addCommentForm = document.getElementById("jsAddComment");

// 3. 
// 3-1. 비디오 id 값만 url에서 split로 잘라서 얻음
// 3-2. axios 이용, 주소창을 "/api/${videoId}/comment" 해당 url로 보냄
// 3-3. 2.에서 사용할 comment 데이터를 "/api/${videoId}/comment"로 보냄
// 4. videoController.js 에서 postAddComment 함수 실행


const sendComment = async comment => {
    const videoId = window.location.href.split("/videos/")[1];
    const response = await axios({
      url: `/api/${videoId}/comment`,
      method: "POST",
      data: {
        comment
      }
    });
    console.log(response);
  };

  // 2. 코멘트 인풋 박스 value 값을 sendComment 함수 이용하여 실행
  const handleSubmit = event => {
    event.preventDefault();
    const commentInput = addCommentForm.querySelector("input");
    const comment = commentInput.value;
    sendComment(comment);
    commentInput.value = "";
  };

  function init() {
      // 1. submit시 handleSubmit 함수 실행
    addCommentForm.addEventListener("submit", handleSubmit);
  }

  if (addCommentForm) {
    init();
  }

view/videoDetail.pug

        .video__comments
            if video.comments.length === 1
                span.video__comment-number 1 comment
            else
                span.video__comment-number #{video.comments.length} comments
            form.add__comment#jsAddComment
                input(type="text", placeholder="add a comment")
                ul.video__comments-list
                    each comment in video.comments
                        li
                            span=comment.text