MovieApp 만들기 (댓글 등록, 삭제)

김재훈·2023년 10월 31일

MovieApp 만들기

목록 보기
7/8
// server/model/Reple.js
import mongoose from "mongoose";

const repleSchema = new mongoose.Schema(
  {
    reple: {
      type: String,
      required: true,
    },
    author: {
      type: String,
      ref: "User",
      required: true,
    },
    movieId: {
      type: String,
      required: true,
    },
  },
  { collection: "reples", timestamps: true }
);

const Reple = mongoose.model("Reple", repleSchema);

export default Reple;

댓글에 필요한 댓글 모델 스키마를 만든다.

댓글 불러오기

// client/src/components/reple/RepleList.tsx

  const [repleList, setRepleList] = useState<any>([]);
  const body = { movieId: movieId };

  useEffect(() => {
    axios
      .post("/api/reple/getreple", body)
      .then((res) => {
        if (res.data.success) {
          setRepleList([...res.data.repleList]);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

서버에 영화 아이디를 body로 넘겨주어서 댓글 리스트를 찾고 repleList에 복사한다.

// server/router/Reple.js
import { Router } from "express";
import Reple from "../model/Reple.js";

const router = Router();

router.post("/getreple", (req, res) => {
  const { movieId } = req.body;

  Reple.find({ movieId })
    .then((repleInfo) => {
      return res.status(200).json({ success: true, repleList: repleInfo });
    })
    .catch((err) => {
      return res.status(400).json({ success: false });
    });
});

클라이언트에서 영화 아이디를 넘겨받아 db에서 해당 아이디에 등록된 댓글을 찾는다.

댓글 등록

// client/src/components/reple/RepleUpload.tsx
const [name, setName] = useState<string>("");
const [reple, setReple] = useState<string>("");

useEffect(() => {
    axios.get("/api/user/auth").then((res) => {
      if (res.data.isAuth === true) setName(res.data.name);
    });
  }, []);

  const repleUploadFunc = (e: React.MouseEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!reple) {
      return alert("댓글을 입력해주세요!");
    }

    const body = {
      reple: reple,
      name: name,
      movieId: movieId,
    };

    axios.post("/api/reple/submit", body).then((res) => {
      if (res.data.success) {
        alert("댓글 작성에 성공하였습니다.");
        window.location.reload();
      } else {
        alert("댓글 작성에 실패하였습니다.");
      }
    });
  };

먼저 로그인을 한 상태인지 검사를 하고 확인이 되면 댓글 등록시 유저 이름을 로그인된 아이디로 세팅한다.

그리고 댓글을 입력하면 댓글, 유저 이름, 영화 아이디를 body에 담아서 서버에 넘겨준다.

댓글 작성에 성공하면 새로고침을 한다.

// server/router/Reple.js
import { Router } from "express";
import Reple from "../model/Reple.js";

const router = Router();

router.post("/submit", (req, res) => {
  const temp = {
    reple: req.body.reple,
    movieId: req.body.movieId,
    author: req.body.name,
  };

  const newReple = new Reple(temp);

  newReple
    .save()
    .then(() => {
      return res.status(200).json({ success: true });
    })
    .catch((err) => {
      return res.status(400).json({ success: false });
    });
});

클라이언트에서 댓글에 대한 정보를 받아와 db에 저장한다.

댓글 삭제

// client/src/components/reple/RepleContent.tsx

const [flag, setFlag] = useState<boolean>(false);

useEffect(() => {
  axios.get("/api/user/auth").then((res) => {
    if (res.data.isAuth !== true) return;
    
    if (res.data.name === reple.author) return setFlag(true);
  });
}, [flag]);

미들웨어 auth를 통해 로그인 상태를 확인하고 현재 로그인된 아이디와 댓글을 등록한 아이디가 동일하면 flag를 true로 바꿔서 삭제 권한을 준다.

// client/src/components/reple/RepleContent.tsx

const repleDeleteFunc = (e: React.MouseEvent<HTMLElement>) => {
  e.preventDefault();

  if (window.confirm("정말로 삭제하시겠습니까?")) {
    const body = {
      repleId: reple._id,
      movieId: reple.movieId,
    };
    axios
      .post("/api/reple/delete", body)
      .then((res) => {
      if (res.data.success) {
        alert("댓글이 삭제되었습니다");
        window.location.reload();
      }
    })
      .catch((err) => {
      alert("댓글 삭제에 실패하였습니다.");
    });
  }
};

댓글 삭제 버튼을 누르면 해당 댓글 아이디와 영화 아이디를 body에 담아서 서버에 넘겨준다.

// server/router/Reple.js

router.post("/delete", (req, res) => {
  Reple.deleteOne({ _id: req.body.repleId })
    .then(() => {
      return res.status(200).json({ success: true });
    })
    .catch((err) => {
      console.log(err);
      return res.status(400).json({ success: false });
    });
});

클라이언트에서 받아온 댓글 아이디를 db에서 찾아서 삭제한다.

profile
김재훈

0개의 댓글