Skip to content

Commit

Permalink
Merge pull request #101 from UMC-ON/feat/comment
Browse files Browse the repository at this point in the history
Fix: 댓글과 답글 paging 조회 수정
  • Loading branch information
sanggae4133 authored Nov 14, 2024
2 parents 1377a16 + 5f147e8 commit 633dfec
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@
import com.on.server.global.common.ResponseCode;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
Expand All @@ -33,14 +36,29 @@ public class CommentService {
private final FcmService fcmService;
private final AlertService alertService;

// 특정 게시글의 모든 댓글 및 답글 조회
// 특정 게시글의 댓글을 페이징으로 조회하고, 댓글에 대한 모든 답글을 반환
@Transactional(readOnly = true)
public Page<CommentResponseDTO> getAllCommentsAndRepliesByPostId(Long postId, Pageable pageable) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new BadRequestException(ResponseCode.ROW_DOES_NOT_EXIST, "게시글을 찾을 수 없습니다. ID: " + postId));

Page<Comment> comments = commentRepository.findByPost(post, pageable);
return comments.map(comment -> CommentResponseDTO.from(comment, commentRepository));
Page<Comment> parentComments = commentRepository.findByPost(post, pageable);

List<CommentResponseDTO> responseDTOs = parentComments.stream()
.flatMap(parentComment -> {
List<CommentResponseDTO> result = new ArrayList<>();
result.add(CommentResponseDTO.from(parentComment, commentRepository));

List<Comment> replies = commentRepository.findAllByParentComment(parentComment);
result.addAll(replies.stream()
.map(reply -> CommentResponseDTO.from(reply, commentRepository))
.collect(Collectors.toList()));

return result.stream();
})
.collect(Collectors.toList());

return new PageImpl<>(responseDTOs, pageable, parentComments.getTotalElements());
}

// 특정 댓글의 모든 답글 조회
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@
import java.util.List;

public interface CommentRepository extends JpaRepository<Comment, Long> {
// 게시글의 모든 댓글 및 답글 조회
Page<Comment> findByPost(Post post, Pageable pageable);
// 게시글의 댓글 페이징해서 조회
@Query("SELECT c FROM Comment c WHERE c.post = :post AND c.parentComment IS NULL")
Page<Comment> findByPost(@Param("post") Post post, Pageable pageable);

// 댓글에 대한 답글 조회
List<Comment> findAllByParentComment(Comment parentComment);

// 댓글에 대한 답글 페이징해서 조회
Page<Comment> findByParentComment(Comment parentComment, Pageable pageable);

// 사용자가 게시글에 작성한 익명 댓글 조회
Expand Down

0 comments on commit 633dfec

Please sign in to comment.