SNS 제작 (댓글 목록 조회)

개발연습생log·2023년 1월 5일
0

SNS 제작

목록 보기
10/15
post-thumbnail

✨개요

🏃 목표

📢 댓글을 조회하는 기능을 구현하자.

📢 요구 사항

  • 댓글 조회는 모든 회원이 권한을 가진다.
  • 제목, 글쓴이, 작성날짜가 표시된다.
  • 목록 기능은 페이징 기능이 포함된다.
    • 한 페이지 당 댓글 갯수는 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));
    }

📌 댓글 목록 조회 서비스 구현

CommentService 메서드 추가

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);
    }

CommentRepository 메서드 추가

Page<Comment> findByPost(Pageable pageable, Post post);

CommentResponse 메서드 추가

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;
    }

📖 회고

  • 지금까지는 했던 것을 구현하는 것이라 어렵지 않았지만
  • 다음 알람, 좋아요 기능은 한번도 구현하지 않은 유형의 기능이라 조금 어려울 것 같다.
profile
주니어 개발자를 향해서..

0개의 댓글