ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 8월 10일 목요일 TIL 회고록
    카테고리 없음 2023. 8. 11. 01:06

    댓글 좋아요 API 개발


    먼저 댓글 좋아요 (CommentLike) 엔티티를 만들었다.

     

    유저 한명이 여러개의 좋아요를 누를 수 있으니 ManyToOne, 하나의 댓글에 여러개의 좋아요를 누를 수 있으니 ManyToOne 어노테이션을 사용했다.

     

    CommentLike.class

    @Entity
    @Getter
    @NoArgsConstructor(access = AccessLevel.PROTECTED)
    public class CommentLike {
    
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "COMMENT_LIKE_ID")
      private Long Id;
    
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "USER_ID")
      private User user;
    
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "COMMENT_ID")
      private Comment comment;
    
      public CommentLike(User user, Comment comment) {
        this.user = user;
        this.comment = comment;
      }
    }

     

    그 다음 컨트롤러에 좋아요 추가, 좋아요 취소 기능을 만들었다.

    RequestParam 어노테이션 대신에 PathVariable 어노테이션을 사용했다.

     

    CommentController.class

    // 댓글 좋아요
      @PostMapping("/comments/like/{commentId}")
      public ResponseEntity<String> commentLikePost(@PathVariable Long commentId,
          @AuthenticationPrincipal UserDetailsImpl userDetails) {
        commentLikeService.commentLikePost(commentId, userDetails.getUser());
        return new ResponseEntity<>("댓글 좋아요!", HttpStatus.OK);
      }
    
      // 댓글 좋아요 취소
      @DeleteMapping("/comments/like/{commentId}")
      public ResponseEntity<String> commentLikeDelete(@PathVariable Long commentId,
          @AuthenticationPrincipal UserDetailsImpl userDetails) {
        commentLikeService.commentLikeDelete(commentId, userDetails.getUser());
        return new ResponseEntity<>("댓글 좋아요 취소!", HttpStatus.OK);
      }

     

    서비스에서 댓글 좋아요, 좋아요 취소 기능을 구현했다.

     

    CommentLikeServiceImpl.class

    // 댓글 좋아요
      @Override
      public void commentLikePost(Long commentId, User user) {
    
        Comment comment = commentRepository.findById(commentId).orElseThrow(
            () -> new CustomException(ExceptionStatus.COMMENT_NOT_FOUND)
        );
    
        if (existsCommentLikeCommentIdAndUserId(commentId, user.getId())) {
          throw new IllegalStateException("이미 좋아요를 누르셨습니다");
    
        } else {
          CommentLike commentLike = new CommentLike(user, comment);
          commentLikeRepository.save(commentLike);
        }
    
      }
    
      // 댓글 좋아요 취소
      @Override
      public void commentLikeDelete(Long commentId, User user) {
        if (!existsCommentLikeCommentIdAndUserId(commentId, user.getId())) {
          throw new IllegalStateException("좋아요를 누르지 않으셨습니다.");
        } else {
          CommentLike commentLike = commentLikeRepository.findByCommentIdAndUserId(
              commentId, user.getId());
          commentLikeRepository.delete(commentLike);
        }
      }

    댓글 좋아요 프론트엔드 구현


    vs code에서 댓글 좋아요, 좋아요 취소 function을 구현했다.

    	// 댓글 좋아요
        function commentLikePost(commentId) {
          var settings = {
          "url": `http://localhost:8080/api/comments/like/${parseInt(
            commentId
          )}`,
          "method": "POST",
          "timeout": 0,
          "headers": {
            "Authorization": localStorage.getItem('accessToken')
          },
        };
    
        $.ajax(settings).done(function (response) {
          console.log(response);
          reloadComments();
        })
        .fail(function (response) {
          console.log(response)
        });
        }
    
        // 댓글 좋아요 취소
        function commentLikeCancel(commentId) {
          var settings = {
          "url": `http://localhost:8080/api/comments/like/${parseInt(
            commentId
          )}`,
          "method": "DELETE",
          "timeout": 0,
          "headers": {
            "Authorization": localStorage.getItem('accessToken')
          },
        };
    
        $.ajax(settings).done(function (response) {
          console.log(response);
          reloadComments();
        })
        .fail(function (response) {
          console.log(response)
        });
        }

     

    실행 결과

     

    좋아요를 누르지 않았을때

    좋아요를 눌렀을때

     

Designed by Tistory.