Skip to content

Commit

Permalink
BE: [feat] 댓글 삭제 기능 CSID-DGU#36
Browse files Browse the repository at this point in the history
  • Loading branch information
Seoyoung2222 committed Nov 25, 2024
1 parent d1ad333 commit dfb89c5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,13 @@ public ResponseEntity<String> toggleLike(@PathVariable String boardName, @PathVa
String result = commentCommandService.toggleLike(commentId);
return ResponseEntity.ok(result);
}

@DeleteMapping("{commentId}")
public ResponseEntity<Void> deleteComment(
@PathVariable String boardName,
@PathVariable Long postId,
@PathVariable Long commentId) {
commentCommandService.deleteComment(commentId);
return ResponseEntity.noContent().build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@

public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findByPostIdAndParentCommentIsNull(Long postId);
List<Comment> findByParentCommentId(Long parentCommentId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@
import RunningMachines.R2R.domain.user.repository.UserRepository;
import RunningMachines.R2R.domain.user.service.AuthCommandService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class CommentCommandService {
Expand Down Expand Up @@ -62,11 +65,35 @@ public String toggleLike(Long commentId) {
}
}

@Transactional
public void deleteComment(Long commentId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new IllegalArgumentException("댓글을 찾을 수 없습니다"));

validateWriter(comment);

List<Comment> replies = commentRepository.findByParentCommentId(commentId);
if (!replies.isEmpty()) {
commentRepository.deleteAll(replies);
}
commentLikeRepository.deleteAll(comment.getHearts());
commentRepository.delete(comment);

log.info("댓글 삭제 완료");
}

@Transactional(readOnly = true)
public long getLikeCount(Long commentId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new IllegalArgumentException("댓글을 찾을 수 없습니다."));

return commentLikeRepository.countByComment(comment);
}

private void validateWriter(Comment comment) {
User currentUser = authCommandService.getCurrentUser();
if (!comment.getUser().equals(currentUser)) {
throw new IllegalArgumentException("작성자만 댓글을 삭제할 수 있습니다");
}
}
}

0 comments on commit dfb89c5

Please sign in to comment.