✨개요
🏃 목표
📢 댓글을 조회하는 기능을 구현하자.
📢 요구 사항
- 댓글 조회는 모든 회원이 권한을 가진다.
- 제목, 글쓴이, 작성날짜가 표시된다.
- 목록 기능은 페이징 기능이 포함된다.
- 한 페이지 당 댓글 갯수는 10개이다.
- 작성날짜 기준으로 최신순으로 sort한다.
📜 접근방법
✅ TO-DO
🔧 구현
📌 댓글 목록 조회 컨트롤러 테스트 작성
<@Test
@DisplayName("댓글 목록 조회 성공")
@WithMockUser
void comment_get_list_SUCCESS() throws Exception {
mockMvc.perform(get("/api/v1/posts/1/comments")
.with(csrf())
.param("page", "0")
.param("size", "10")
.param("sort", "createdAt,desc"))
.andExpect(status().isOk());
ArgumentCaptor<Pageable> pageableArgumentCaptor = ArgumentCaptor.forClass(Pageable.class);
verify(commentService).getComments(pageableArgumentCaptor.capture(), any());
PageRequest pageRequest = (PageRequest) pageableArgumentCaptor.getValue();
assertEquals(0, pageRequest.getPageNumber());
assertEquals(10, pageRequest.getPageSize());
assertEquals(Sort.by(Sort.Direction.DESC, "createdAt"), pageRequest.getSort());
}
📌 댓글 목록 조회 컨트롤러 구현
@GetMapping
public ResponseEntity<Response> getComments(@PageableDefault(size = 10) @SortDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable, @PathVariable Long postId){
Page<CommentResponse> commentResponses = commentService.getComments(pageable,postId);
return ResponseEntity.ok().body(Response.of("SUCCESS",commentResponses));
}
📌 댓글 목록 조회 서비스 구현
public Page<CommentResponse> getComments(Pageable pageable, Long postId) {
Post findPost = AppUtil.findPost(postRepository, postId);
Page<Comment> comments = commentRepository.findByPost(pageable, findPost);
return CommentResponse.listOf(comments);
}
Page<Comment> findByPost(Pageable pageable, Post post);
public static Page<CommentResponse> listOf(Page<Comment> comments) {
Page<CommentResponse> commentResponses = comments.map(m -> CommentResponse.builder()
.id(m.getId())
.comment(m.getComment())
.userName(m.getUser().getUserName())
.postId(m.getPost().getId())
.createdAt(m.getCreatedAt())
.build());
return commentResponses;
}
📖 회고
- 지금까지는 했던 것을 구현하는 것이라 어렵지 않았지만
- 다음 알람, 좋아요 기능은 한번도 구현하지 않은 유형의 기능이라 조금 어려울 것 같다.