만능재주꾼

[Node.js 교과서] 팔로우하기, 팔로잉끊기 구현 본문

💻 Node.js

[Node.js 교과서] 팔로우하기, 팔로잉끊기 구현

유고랭 2021. 3. 7. 00:13

✔️ 팔로우 하기

  1. 팔로우한 목록에 없으면 팔로우하기 버튼 나타내기 (main.html)
<!-- 팔로우 아이디 리스트에 해당 게시물 사용자의 아이디가 없다면 팔로우하기 버튼 생성-->

{% if not followerIdList.includes(twit.User.id) and twit.User.id !== user.id %}
  <button class="twit-follow">팔로우하기</button>

    2.  버튼 이벤트 코드 작성하기 (main.html)

/* 해당 클래스의 버튼이 눌리면 팔로우 여부 묻기*/

document.querySelectorAll('.twit-follow').forEach(function(tag) {
   tag.addEventListener('click', function() {
      const myId = document.querySelector('#my-id');
      
      if (myId) { //로그인한 사용자가 있는지 확인
         const userId = tag.parentNode.querySelector('.twit-user-id').value;
         
         if (userId !== myId.value) { //로그인한 사용자와 팔로우한 사용자가 다르면 팔로잉 여부 묻기
            if (confirm('팔로잉하시겠습니까?')) { //팔로잉 yes면
              axios.post(`/user/${userId}/follow`) //routes/user.js의 follow 코드 부르기
                .then(() => {
                  location.reload();
                })
                .catch((err) => {
                  console.error(err);
                });
          }
       }
   }
});

    3.  routes/user.js에 follow 코드 작성하기 (routes/user.js)

/* 팔로우 기능 */

router.post('/:id/follow', isLoggedIn, async (req, res, next) => {
  try {
    const user = await User.findOne({ where: { id: req.user.id } }); //아이디 가져오기
    if (user) { //아이디 있으면
      await user.addFollowing(parseInt(req.params.id, 10)); //팔로우할 사용자를 찾아서 addFollowing 메서드로 현재 로그인된 사용자와 관계 지정
      res.send('success');
    } else {
      res.status(404).send('no user');
    }
  } catch (error) {
    console.error(error);
    next(error);
  }
});

✔️ 팔로잉 끊기

  1. 팔로잉한 사용자에 한해 팔로잉끊기 버튼 만들기(main.html)
{% if not followerIdList.includes(twit.User.id) and twit.User.id !== user.id %}
   <button class="twit-follow">팔로우하기</button>
   
<!-- 팔로잉하기 코드에 덧붙여 해당 코드 작성 -->
{% else %}
<button class="twit-notfollow">팔로잉끊기</button>

 

    2.  버튼 이벤트 코드 작성하기(main.html)

/* 해당 클래스의 버튼이 눌리면 팔로잉 끊기 여부 묻기 */

document.querySelectorAll('.twit-notfollow').forEach(function(tag){
   tag.addEventListener('click',function(){
      const myId = document.querySelector('#my-id');
      if (myId){ //로그인된 사용자 존재하면
         const userId = tag.parentNode.querySelector('.twit-user-id');
         if (myId !== userId){ //현재 사용자와 팔로잉끊기한 사용자가 다르면
            if (confirm('팔로잉을 끊으시겠습니까?')){ //팔로잉끊기 여부 묻기
               axios.post(`/user/${userId}/notfollow`) //routes/user.js의 notfollow 코드로 이동
                .then(()=>{
                 location.reload();
                })
                .catch((error)=>{
                 console.error(error);
                });
             }
          }
       }
   });
});

    3.  routes/user.js에 notfollow 코드 작성하기 (routes/user.js)

/* 팔로잉 끊기 기능 */

router.post('/:id/notfollow', isLoggedIn, async(req,res,next) => {
  try{
    const user = await User.findOne({ where: {id: req.params.id } });
    if (user){ //데이터베이스에서 찾은 사용자가 있다면
      await User.removeFollower(parseInt(req.user.id)); //팔로잉 끊기
      res.send('success');
    }
  } catch (error){ 
    next(error);
  }
});

 

Comments