#TIL 5일차(미니프로젝트 회고)

앙꼬·2024년 4월 24일

부트캠프

목록 보기
5/59


기능 구현 코드 목록

댓글 저장

<script>
// 댓글 저장
    $("#submit").click(async function () {
      let nickname = $(`#nickname`).val();
      let password = $(`#password`).val();
      let comment = $(`#comment`).val();

      let empty = [];

      // 빈 필드를 확인하고 빈 필드에 대한 메시지를 배열에 추가
      if (!nickname) empty.push("닉네임");
      if (!password) empty.push("비밀번호");
      if (!comment) empty.push("댓글");

      // 빈 필드의 수에 따라 알림 메시지 다르게 구성
      switch (empty.length) {
        case 0:
          break; // 댓글 작성 성공
        case 1:
          alert(`${empty[0]} 입력하세요.`);
          return;
        case 2:
          alert(`${empty.join(", ")} 입력하세요.`);
          return;
        default:
          alert("항목에 입력해주세요!")
          return;
      }

      // 비밀번호가 4자 아닌 경우 
      if (password.length !== 4) {
        alert("비밀번호는 4글자여야 합니다. 다시 입력하세요.");
        return;
      }

      let doc = {
        nickname: nickname,
        password: password,
        comment: comment,
        createdAt: serverTimestamp(),
      };

      await addDoc(collection(db, "jsbComments"), doc);
      alert("작성 완료!");
      window.location.reload();
    });

    // 페이지에 데이터 가져오기
    const querySnapshot = await getDocs(collection(db, "jsbComments"));

    // QuerySnapshot에서 DocumentSnapshot 배열로 변환
    const docs = querySnapshot.docs;

    // 댓글을 작성된 시간으로 내림차순으로 정렬
    docs.sort((a, b) => {
        return b.data().createdAt - a.data().createdAt;
    });

    docs.forEach((doc) => {
      let row = doc.data();
      let nickname = row["nickname"];
      let password = row["password"];
      let comment = row["comment"];
      
      // 타임스탬프
      let createdAtTimestamp = row["createdAt"];
      let createdAt = new Date(createdAtTimestamp.seconds * 1000);
      let date = new Intl.DateTimeFormat("ko-KR", {
        year: "numeric",
        month: "numeric",
        day: "numeric",
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
        hour12: true
    }).format(createdAt);
    </script>

댓글 수정

<script>
// 댓글 수정
    $(`#comments`).on('click', '.update', async function () {
    const docId = $(this).attr('data-docid');
    // 사용자로부터 입력된 비밀번호
    let password = prompt("비밀번호를 입력하세요.");
    // 데이터베이스에서 해당 댓글 문서 가져오기
    const docRef = doc(db, "jsbComments", docId);
    const docSnap = await getDoc(docRef); 
    if (docSnap.exists()) {
        const data = docSnap.data();   

        // 데이터베이스에 저장된 비밀번호와 사용자로부터 입력된 비밀번호 비교
        if (password === data.password) {
            // 사용자로부터 수정할 내용 입력 받기
            console.log("dddd");
            let newComment = prompt("수정할 내용을 입력하세요.");
            // 수정할 내용이 비어 있는지 확인
            if (newComment.trim() === "") {
                alert("내용이 입력되지 않았습니다!");
            }else {
                // 수정된 내용을 문서에 반영하기
                await updateDoc(docRef, {
                    comment: newComment
                });
                alert("수정 완료!");
                window.location.reload();
            }
        } else {
            alert("비밀번호가 일치하지 않습니다.");
        }
    }
});
</script>

댓글 삭제

<script>
 // 댓글 삭제
    $('#comments').on('click', '.delete', async function () {
    const docId = $(this).attr('data-docid');
    // 사용자로부터 입력된 비밀번호
    let password = prompt("비밀번호를 입력하세요.");
    // 데이터베이스에서 해당 댓글 문서 가져오기
    const docRef = await doc(db, "jsbComments", docId);
    const docSnap = await getDoc(docRef); 
    if (docSnap.exists()) {
        const data = docSnap.data();       
        // 데이터베이스에 저장된 비밀번호와 사용자로부터 입력된 비밀번호 비교
        if (password === data.password) {
            await deleteDoc(docRef);
            alert("삭제 완료!");
            window.location.reload();
        }else if(password !== data.password){
            alert("비밀번호가 일치하지 않습니다. 다시 시도해주세요");
        }
    }
});
</script>
profile
프론트 개발자 꿈꾸는 중

0개의 댓글