댓글 수정/삭제 기능

Sol's·2023년 1월 11일

프로젝트

목록 보기
15/16

자 이제 댓글 수정/삭제 기능을 만들것이다.

댓글 수정/삭제 기능

Controller

Authentication에서 UserName을 가져와 사용한다.
게시글에 달린 Comment를 확인할 것이여서 PostId를 받아온다.
수정할 Comment의 id를 받아온다.

//댓글 수정
    @PutMapping("/{postId}/comments/{id}")
    @ApiOperation(value = "댓글 수정", notes = "댓글 작성자만 댓글 수정")
    public Response<CommentResponse> modify(@RequestBody CommentRequest commentRequest, @PathVariable Long postId, @PathVariable Long id,
                                            Authentication authentication) {
        return Response.success(commentService.modify(commentRequest, postId, id, authentication.getName()));
    }
    //댓글 삭제
    @DeleteMapping("/{postId}/comments/{id}")
    @ApiOperation(value = "댓글 삭제")
    public Response<CommentDeleteResponse> delete(@PathVariable Long postId, @PathVariable Long id, Authentication authentication) {
        return Response.success(commentService.delete(postId, id, authentication.getName()));
    }
    }

  

Dto

@AllArgsConstructor
@Getter
@Builder
public class CommentResponse {
    private Long id;
    private String comment;
    private String userName;
    private Long postId;

    private LocalDateTime createdAt;
    private LocalDateTime lastModifiedAt;

    public static CommentResponse fromEntity(Comment comment) {
        return CommentResponse.builder()
                .id(comment.getId())
                .comment(comment.getComment())
                .userName(comment.getUser().getUserName())
                .postId(comment.getPost().getId())
                .createdAt(comment.getCreatedAt())
                .lastModifiedAt(comment.getLastModifiedAt())
                .build();
    }
}
@Getter
@AllArgsConstructor
public class CommentDeleteResponse {
    private String message;
    private Long id;

    public static CommentDeleteResponse of(Long postId) {
        return new CommentDeleteResponse("댓글 삭제 완료", postId);
    }
}

Service

공통로직
수정과 삭제시 Comment를 찾고 Post가있는지 확인하는 로직이 공통부분이여서 따로 메소드로 빼주었다.

private Comment checkCommentAndPost(Long postId, Long commentId) {
        //Comment를 찾는다.
        Comment comment = commentRepository.findById(commentId).orElseThrow(() ->
                new AppException(ErrorCode.COMMENT_NOT_FOUND, ErrorCode.COMMENT_NOT_FOUND.getMessage()));
        //Post가 있는지 확인
        postService.getPostById(postId);
        return comment;
    }

댓글 수정

  1. Comment와 Post를 찾는다.
  2. Post에 Comment가 작성되었는지 일치하는지 확인
  3. 같은 유저가 작성한 것인지 확인
  4. CommentService에 @Transactional 어노테이션으로 set으로 Entity의 내용을 변경하면 자동으로 update가 된다.
  public CommentDeleteResponse delete(Long postId, Long commentId, String userName) {

        //Comment를 찾는다.
        Comment comment = checkCommentAndPost(postId, commentId);

        // Post에 Comment가 작성되었는지 일치하는지 확인
        if (!comment.getPost().getId().equals(postId)) {
            throw new AppException(ErrorCode.ID_NOT_MATCH,ErrorCode.ID_NOT_MATCH.getMessage());
        }
        // comment를 작성한 작성자가 맞는지 확인
        if(!comment.getUser().getUserName().equals(userName) ){
            throw new AppException(ErrorCode.INVALID_PERMISSION, ErrorCode.INVALID_PERMISSION.getMessage());
        }

        //삭제
        comment.deleteSoftly(LocalDateTime.now());
        return CommentDeleteResponse.of(commentId);
    }

댓글 삭제
1. Comment와 Post를 찾는다.
2. Post에 Comment가 작성되었는지 일치하는지 확인
3. 같은 유저가 작성한 것인지 확인
4. CommentService에 @Transactional 어노테이션과 앞서구현한 Soft Delete로 논리적 삭제를 한다.

    //Comment를 찾는다.
        Comment comment = checkCommentAndPost(postId, commentId);

        // Post에 Comment가 작성되었는지 일치하는지 확인
        if (!comment.getPost().getId().equals(postId)) {
            throw new AppException(ErrorCode.ID_NOT_MATCH,ErrorCode.ID_NOT_MATCH.getMessage());
        }
        // comment를 작성한 작성자가 맞는지 확인
        if(!comment.getUser().getUserName().equals(userName) ){
            throw new AppException(ErrorCode.INVALID_PERMISSION, ErrorCode.INVALID_PERMISSION.getMessage());
        }

        //삭제
        comment.deleteSoftly(LocalDateTime.now());
        return CommentDeleteResponse.of(commentId);

Repositoy

  • List를 조회할떄 Pageing 처리를 해주기 위해 따로 JPA메소드를 설정해 주었다.
public interface CommentRepository extends JpaRepository<Comment, Long> {
    Page<Comment> findByPostId(Long id, Pageable pageable);
}

profile
배우고, 생각하고, 행동해라

0개의 댓글