프로젝트 (Java)/예약마켓

[프로젝트] 16. 게시물 전체 조회 및 ID로 상세 정보 조회

hihyuk 2024. 1. 26. 09:53

PostController 구현

PostController에서는 게시물 전체 조회를 위한 getPosts 메소드와 특정 게시물 상세 조회를 위한 getPostById 메소드를 정의합니다.

@RestController
@RequestMapping("/api/posts")
@RequiredArgsConstructor
public class PostController {
    private final PostService postService;

    @GetMapping
    public List<PostDto> getPosts() {
        return postService.getPosts();
    }
    
    @GetMapping("/{post_id}")
    public PostDetailDto getPostById(@PathVariable("post_id") Long postId) {
        return postService.getPostById(postId);
    }
}

 

PostDto 및 PostDetailDto 구현

PostDto는 게시물 목록 조회 시 사용되며, 게시물의 기본적인 정보와 좋아요 수, 댓글 수를 포함합니다. PostDetailDto는 특정 게시물의 상세 정보를 나타내며, 게시물에 포함된 댓글 정보를 CommentDto 리스트로 포함합니다.

PostDto

@Getter
public class PostDto {
    private Long id;
    private String content;
    private String name;
    private String profileImg;
    private Long userId;
    private Integer likeCount;
    private Integer commentCount;

    public PostDto(Post post) {
        id = post.getId();
        content = post.getContent();
        name = post.getUser().getName();
        profileImg = post.getUser().getProfileImg();
        userId = post.getUser().getId();
        likeCount = post.getLikes().size();
        commentCount = post.getComments().size();
    }
}

PostDetailDto

@Getter
public class PostDetailDto {
    private Long id;
    private String content;
    private String name;
    private String profileImg;
    private Long userId;
    private List<CommentDto> comments;

    public PostDetailDto(Post post) {
        id = post.getId();
        content = post.getContent();
        name = post.getUser().getName();
        profileImg = post.getUser().getProfileImg();
        userId = post.getUser().getId();
        comments = post.getComments().stream().map(CommentDto::getCommentDto).collect(Collectors.toList());
    }
}

 

CommentDto 구현

CommentDto는 게시물에 포함된 각 댓글의 정보를 나타냅니다. 댓글 작성자의 이름, 프로필 이미지, 사용자 ID를 포함합니다.

@Getter
@AllArgsConstructor
public class CommentDto {
    private Long id;
    private String content;
    private String name;
    private String profileImg;
    private Long userId;

    public static CommentDto getCommentDto(Comment comment) {
        return new CommentDto(
                comment.getId(),
                comment.getContent(),
                comment.getWriter().getName(),
                comment.getWriter().getProfileImg(),
                comment.getWriter().getId());
    }
}

 

PostService 구현

PostService에서는 게시물 전체 조회와 특정 게시물 조회의 비즈니스 로직을 구현합니다. 각 메소드는 PostRepository를 통해 데이터베이스에서 게시물 데이터를 조회하고, 조회된 데이터를 DTO로 변환하여 반환합니다.

    public List<PostDto> getPosts() {
        List<Post> posts = postRepository.findAll();
        return posts.stream().map(PostDto::new).collect(Collectors.toList());
    }

    public PostDetailDto getPostById(Long postId) {
        Post post = postRepository.findById(postId).orElseThrow(
                () -> new BadRequestException("포스트가 없습니다.")
        );
        return new PostDetailDto(post);
    }

 

결론

이렇게 구현된 게시물 조회 기능을 통해, 사용자는 애플리케이션 내에서 게시물을 쉽게 탐색하고, 관심 있는 게시물의 상세 정보를 확인할 수 있습니다. 이 기능은 사용자 경험을 향상시키며, 애플리케이션의 사용성을 높이는 데 기여합니다.