Skip to content

Commit

Permalink
Merge pull request #52 from IT-Cotato/refactor/comment-#51
Browse files Browse the repository at this point in the history
[Refactor] 댓글 및 게시물 본인작성 여부 확인 필드 추가 및 좋아요 여부 확인 필드 추가
  • Loading branch information
chanmin-00 authored Feb 3, 2025
2 parents 5aafd42 + 3010ecd commit ae02451
Show file tree
Hide file tree
Showing 14 changed files with 100 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ public ResponseEntity<ApiResponse<?>> saveLearningSetsByExcel() {
return ResponseEntity.status(HttpStatus.OK).body(ApiResponse.EMPTY_RESPONSE);
}


@Operation(
summary = "레벨별 학습 세트 조회",
description = "레벨별 전체 학습 세트를 조회합니다. 사용자의 현재 레벨에 해당하는 학습 세트 목록을 반환합니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,11 @@ public ResponseEntity<ApiResponse<Object>> getPopularPosts() {

@Operation(summary = "게시물 상세 조회", description = "게시물의 상세 정보를 조회합니다.")
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<Object>> getPost(final @PathVariable("id") long id) {
public ResponseEntity<ApiResponse<Object>> getPost(
final @AuthenticationPrincipal CustomUserDetails currentUser,
final @PathVariable("id") long id) {

PostDTO postDTO = postService.getPost(id);
PostDTO postDTO = postService.getPost(id, currentUser.getId());
return ResponseEntity.status(HttpStatus.OK)
.body(ApiResponse.from(PostResponse.toPostResponse(postDTO)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ public ResponseEntity<ApiResponse<Object>> getToktoks(

@Operation(summary = "경제 톡톡 게시물 상세 조회", description = "경제 톡톡 게시물을 상세 조회합니다.")
@GetMapping("/toktok/{id}")
public ResponseEntity<ApiResponse<Object>> getToktok(final @PathVariable("id") long id) {
public ResponseEntity<ApiResponse<Object>> getToktok(
final @AuthenticationPrincipal CustomUserDetails currentUser,
final @PathVariable("id") long id) {

PostDTO postDTO = toktokService.getToktok(id);
PostDTO postDTO = toktokService.getToktok(id, currentUser.getId());

return ResponseEntity.status(HttpStatus.OK)
.body(ApiResponse.from(ToktokResponse.toToktokResponse(postDTO)));
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/com/ripple/BE/post/domain/Comment.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
import jakarta.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -60,6 +61,10 @@ public class Comment extends BaseEntity {
@Column(name = "is_deleted", nullable = false)
private boolean isDeleted = false; // 삭제 여부

@Setter @Transient private Boolean isAuthor; // 작성자 여부

@Setter @Transient private Boolean isLiked; // 좋아요 여부

private long replyCount = 0L; // 답글 수

@OneToMany(mappedBy = "comment", cascade = CascadeType.ALL, orphanRemoval = true)
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/ripple/BE/post/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ public class Post extends BaseEntity {

@Setter @Transient private Boolean isScrapped;

@Setter @Transient private Boolean isLiked;

@Setter @Transient private Boolean isAuthor;

@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Comment> commentList = new ArrayList<>(); // 댓글 목록

Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/ripple/BE/post/dto/CommentDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public record CommentDTO(
long likeCount,
CommunityUserDTO commenter,
boolean isDeleted,
boolean isLiked,
boolean isAuthor,
long replyCount,
List<CommentDTO> children,
@JsonSerialize(using = LocalDateTimeSerializer.class)
Expand All @@ -31,6 +33,8 @@ public static CommentDTO toCommentDTO(Comment comment) {
comment.getLikeCount(),
CommunityUserDTO.toCommunityUserDTO(comment.getCommenter()),
comment.isDeleted(),
comment.getIsLiked(),
comment.getIsAuthor(),
comment.getReplyCount(),
comment.getChildren().stream().map(CommentDTO::toCommentDTO).toList(),
comment.getCreatedDate(),
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/ripple/BE/post/dto/PostDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public record PostDTO(
Long scrapCount,
ImageListDTO imageList,
Boolean isScraped,
Boolean isLiked,
Boolean isAuthor,
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
LocalDateTime createdDate,
Expand All @@ -49,6 +51,8 @@ public static PostDTO toPostDTO(final Post post) {
post.getScrapCount(),
ImageListDTO.toImageListDTO(post.getImageList()),
post.getIsScrapped(),
post.getIsLiked(),
post.getIsAuthor(),
post.getCreatedDate(),
post.getModifiedDate(),
post.getUsedDate(),
Expand All @@ -67,6 +71,8 @@ public static PostDTO toPostDTO(final Post post, final CommentListDTO commentLis
post.getScrapCount(),
ImageListDTO.toImageListDTO(post.getImageList()),
post.getIsScrapped(),
post.getIsLiked(),
post.getIsAuthor(),
post.getCreatedDate(),
post.getModifiedDate(),
post.getUsedDate(),
Expand All @@ -88,6 +94,8 @@ public static PostDTO toPostDTO(final PostRequest postRequest) {
null,
null,
null,
null,
null,
null);
}

Expand All @@ -106,6 +114,8 @@ public static PostDTO toPostDTO(final PostUpdateRequest request) {
null,
null,
null,
null,
null,
null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ public record CommentResponse(
String commenterName,
String commenterProfileImageUrl,
boolean isDeleted,
boolean isAuthor,
boolean isLiked,
long replyCount,
String createdDate,
List<CommentResponse> children) {
Expand All @@ -25,6 +27,8 @@ public static CommentResponse toCommentResponse(CommentDTO commentDTO) {
commentDTO.commenter().nickname(),
commentDTO.commenter().profileImage().url(),
commentDTO.isDeleted(),
commentDTO.isAuthor(),
commentDTO.isLiked(),
commentDTO.replyCount(),
RelativeTimeFormatter.formatRelativeTime(commentDTO.createdDate()),
commentDTO.children().stream().map(CommentResponse::toCommentResponse).toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public record PostResponse(
long likeCount,
long commentCount,
long scrapCount,
boolean isScraped,
boolean isLiked,
boolean isAuthor,
List<ImageResponse> imageList,
String createdDate,
CommentListResponse commentListResponse) {
Expand All @@ -31,6 +34,9 @@ public static PostResponse toPostResponse(PostDTO postDTO) {
postDTO.likeCount(),
postDTO.commentCount(),
postDTO.scrapCount(),
postDTO.isScraped(),
postDTO.isLiked(),
postDTO.isAuthor(),
postDTO.imageList().imageDTOList().stream().map(ImageResponse::toImageResponse).toList(),
RelativeTimeFormatter.formatRelativeTime(postDTO.createdDate()),
CommentListResponse.toCommentListResponse(postDTO.commentListDTO()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ public record ToktokResponse(
long participantCount,
List<String> imageList,
String createdDate,
boolean isScraped,
boolean isLiked,
CommentListResponse commentListResponse) {

public static ToktokResponse toToktokResponse(PostDTO postDTO) {
Expand All @@ -23,6 +25,8 @@ public static ToktokResponse toToktokResponse(PostDTO postDTO) {
postDTO.commentCount(),
postDTO.imageList().imageDTOList().stream().map(ImageDTO::url).toList(),
RelativeTimeFormatter.formatRelativeTime(postDTO.usedDate().atStartOfDay()),
postDTO.isScraped(),
postDTO.isLiked(),
CommentListResponse.toCommentListResponse(postDTO.commentListDTO()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ public interface CommentRepositoryCustom {

List<Post> findPostsCommentedByUser(Long userId);

List<Comment> findRootCommentsByPost(Post post);
List<Comment> findRootCommentsByPost(Post post, Long userId);
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package com.ripple.BE.post.repository.comment;

import static com.ripple.BE.post.domain.QComment.comment;
import static com.ripple.BE.post.domain.QCommentLike.*;
import static com.ripple.BE.post.domain.QPost.post;

import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ripple.BE.post.domain.Comment;
import com.ripple.BE.post.domain.Post;
import com.ripple.BE.post.domain.QComment;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
Expand All @@ -26,12 +30,31 @@ public List<Post> findPostsCommentedByUser(Long userId) {
}

@Override
public List<Comment> findRootCommentsByPost(Post post) {

return queryFactory
.selectFrom(comment)
.where(comment.post.eq(post).and(comment.parent.isNull())) // 대댓글이 아닌 경우 필터링
.orderBy(comment.createdDate.asc())
.fetch();
public List<Comment> findRootCommentsByPost(Post post, Long userId) {
List<Tuple> results =
queryFactory
.select(comment, commentLike.id)
.from(comment)
.leftJoin(comment.children)
.fetchJoin()
.leftJoin(commentLike)
.on(comment.id.eq(commentLike.comment.id).and(commentLike.user.id.eq(userId)))
.where(comment.post.eq(post))
.orderBy(comment.createdDate.asc())
.fetch();

return results.stream()
.map(
tuple -> {
Comment comment = tuple.get(QComment.comment);
if (comment != null) {
Long likeId = tuple.get(commentLike.id);
comment.setIsLiked(likeId != null);
comment.setIsAuthor(comment.getCommenter().getId().equals(userId));
}
return comment;
})
.filter(comment -> comment.getParent() == null)
.collect(Collectors.toList());
}
}
20 changes: 12 additions & 8 deletions src/main/java/com/ripple/BE/post/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -150,18 +150,22 @@ public PostListDTO getPopularPosts() {
}

@Transactional(readOnly = true)
public PostDTO getPost(final long id) {
public PostDTO getPost(final long id, final long userId) {
Post post = postRepository.findById(id).orElseThrow(() -> new PostException(POST_NOT_FOUND));

CommentListDTO commentListDTO = getCommentList(post);
post.setIsAuthor(post.getAuthor().getId() == userId);
post.setIsLiked(postLikeRepository.existsByPostIdAndUserId(id, userId));
post.setIsScrapped(postScrapRepository.existsByPostIdAndUserId(id, userId));

CommentListDTO commentListDTO = getCommentList(post, userId);

return PostDTO.toPostDTO(post, commentListDTO);
}

@Transactional(readOnly = true)
public CommentListDTO getCommentList(final Post post) {
public CommentListDTO getCommentList(final Post post, final long userId) {

List<Comment> commentList = commentRepository.findRootCommentsByPost(post);
List<Comment> commentList = commentRepository.findRootCommentsByPost(post, userId);

return CommentListDTO.toCommentListDTO(commentList);
}
Expand Down Expand Up @@ -288,10 +292,10 @@ public void addReplyToComment(
Post post = findPostByIdForUpdate(postId);
User user = userService.findUserById(userId);

Comment parent =
commentRepository
.findByIdAndCommenterId(commentId, userId)
.orElseThrow(() -> new PostException(COMMENT_NOT_FOUND));
Comment parent = findCommentByIdForUpdate(commentId);
if (parent.isDeleted() || parent.getParent() != null) {
throw new PostException(COMMENT_NOT_FOUND);
}

Comment comment = Comment.toCommentEntity(content);
comment.setUser(user);
Expand Down
17 changes: 12 additions & 5 deletions src/main/java/com/ripple/BE/post/service/ToktokService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.ripple.BE.post.service;

import static com.ripple.BE.post.domain.type.PostType.*;
import static com.ripple.BE.post.exception.errorcode.PostErrorCode.*;

import com.ripple.BE.post.domain.Comment;
Expand All @@ -12,6 +11,8 @@
import com.ripple.BE.post.exception.PostException;
import com.ripple.BE.post.repository.comment.CommentRepository;
import com.ripple.BE.post.repository.post.PostRepository;
import com.ripple.BE.post.repository.postlike.PostLikeRepository;
import com.ripple.BE.post.repository.postscrap.PostScrapRepository;
import java.time.LocalDate;
import java.util.List;
import java.util.Random;
Expand All @@ -30,6 +31,8 @@
public class ToktokService {

private final PostRepository postRepository;
private final PostLikeRepository postLikeRepository;
private final PostScrapRepository postScrapRepository;
private final CommentRepository commentRepository;

private static final int PAGE_SIZE = 10;
Expand All @@ -46,13 +49,17 @@ public PostDTO getTodayToktok() {
}

@Transactional(readOnly = true)
public PostDTO getToktok(final long id) {
public PostDTO getToktok(final long id, final long userId) {
Post post = postRepository.findById(id).orElseThrow(() -> new PostException(POST_NOT_FOUND));
if (post.getUsedDate() == null) {
throw new PostException(POST_NOT_FOUND);
}

CommentListDTO commentListDTO = getCommentList(post);
post.setIsAuthor(false);
post.setIsLiked(postLikeRepository.existsByPostIdAndUserId(id, userId));
post.setIsScrapped(postScrapRepository.existsByPostIdAndUserId(id, userId));

CommentListDTO commentListDTO = getCommentList(post, userId);

return PostDTO.toPostDTO(post, commentListDTO);
}
Expand All @@ -68,8 +75,8 @@ public PostListDTO getToktoks(final int page, final PostSort sort, final long us
return PostListDTO.toPostListDTO(postPage);
}

private CommentListDTO getCommentList(final Post post) {
List<Comment> commentList = commentRepository.findRootCommentsByPost(post);
private CommentListDTO getCommentList(final Post post, final long userId) {
List<Comment> commentList = commentRepository.findRootCommentsByPost(post, userId);

return CommentListDTO.toCommentListDTO(commentList);
}
Expand Down

0 comments on commit ae02451

Please sign in to comment.