Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ public ResponseEntity<CommentResponse> createPost(
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}

// fixme 게시글 목록 조회 - 정렬 조건 최신순, 좋아요순 추가하였는데 변경될 수 있음
@GetMapping
@Operation(summary = "댓글 목록 조회", description = "게시글 목록을 조회합니다.")
public ResponseEntity<PageResponse<CommentResponse>> getPosts(
Expand All @@ -61,7 +60,9 @@ public ResponseEntity<PageResponse<CommentResponse>> getPosts(
sort
);

Page<CommentResponse> responses = commentService.getComments(cs.getUser().getId(), postId, sortedPageable);
Long userId = (cs != null && cs.getUser() != null) ? cs.getUser().getId() : null;

Page<CommentResponse> responses = commentService.getComments(userId, postId, sortedPageable);
return ResponseEntity.ok(PageResponse.of(responses));
}

Expand Down
18 changes: 10 additions & 8 deletions back/src/main/java/com/back/domain/comment/entity/Comment.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
/**
* 댓글 엔티티.
* 게시글에 대한 사용자 댓글 정보를 저장합니다.
* 계층형 댓글 구조를 지원합니다.
*/
@Entity
@Table(name = "comments",
Expand All @@ -39,13 +38,6 @@ public class Comment extends BaseEntity {
@JoinColumn(name = "post_id", nullable = false)
private Post post;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_comment_id")
private Comment parent;

@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Comment> children = new ArrayList<>();

@Column(nullable = false, columnDefinition = "TEXT")
private String content;

Expand All @@ -66,4 +58,14 @@ public void checkUser(Long userId) {
public void updateContent(String content) {
this.content = content;
}

public void incrementLikeCount() {
this.likeCount++;
}

public void decrementLikeCount() {
if (this.likeCount > 0) {
this.likeCount--;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,18 @@ public final class CommentMappers {

private CommentMappers() {}

public static final Mapper<Comment, CommentResponse> COMMENT_READ = e -> {
public static CommentResponse toCommentResponse(Comment e, User user, boolean liked) {
if (e == null) throw new MappingException("Comment is null");
return new CommentResponse(
e.getId(),
e.isHide() ? "익명" : (e.getUser() != null ? e.getUser().getNickname() : null),
e.getContent(),
e.getLikeCount(),
false, // todo : 내가 쓴 댓글 여부 추후 구현
false, // todo : 좋아요 여부 추후 구현
(user != null && user.getId().equals(e.getUser().getId())),
liked,
e.getCreatedDate()
);
};
}

public static final class CommentCtxMapper implements TwoWayMapper<CommentRequest, Comment, CommentResponse> {
private final User user;
Expand All @@ -58,7 +58,7 @@ public Comment toEntity(CommentRequest req) {

@Override
public CommentResponse toResponse(Comment entity) {
return COMMENT_READ.map(entity);
return toCommentResponse(entity, user, false);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package com.back.domain.comment.repository;

import com.back.domain.comment.entity.Comment;
import jakarta.persistence.LockModeType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
* 댓글 엔티티에 대한 데이터베이스 접근을 담당하는 JpaRepository.
*/
Expand All @@ -17,4 +21,8 @@ public interface CommentRepository extends JpaRepository<Comment, Long> {
Page<Comment> findCommentsByPostId(@Param("postId") Long postId, Pageable pageable);

int countByUserId(Long userId);

@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT c FROM Comment c WHERE c.id = :commentId")
Optional<Comment> findByIdWithLock(@Param("commentId") Long commentId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import com.back.domain.comment.entity.Comment;
import com.back.domain.comment.mapper.CommentMappers;
import com.back.domain.comment.repository.CommentRepository;
import com.back.domain.like.repository.CommentLikeRepository;
import com.back.domain.post.dto.PostSummaryResponse;
import com.back.domain.post.entity.Post;
import com.back.domain.post.repository.PostRepository;
import com.back.domain.user.entity.User;
Expand All @@ -17,6 +19,10 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
* 댓글 관련 비즈니스 로직을 처리하는 서비스.
*/
Expand All @@ -28,6 +34,7 @@ public class CommentService {
private final UserRepository userRepository;
private final PostRepository postRepository;
private final CommentRepository commentRepository;
private final CommentLikeRepository commentLikeRepository;

public CommentResponse createComment(Long userId, Long postId, CommentRequest request) {
User user = userRepository.findById(userId)
Expand All @@ -41,10 +48,23 @@ public CommentResponse createComment(Long userId, Long postId, CommentRequest re
}

public Page<CommentResponse> getComments(Long userId, Long postId, Pageable pageable) {
User user = userId != null
? userRepository.findById(userId).orElse(null)
: null;

Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(ErrorCode.POST_NOT_FOUND));
Page<Comment> commentsPage = commentRepository.findCommentsByPostId(postId, pageable);
return commentsPage.map(CommentMappers.COMMENT_READ::map);

Set<Long> userLikedComments = userId != null
? getUserLikedComments(userId, commentsPage)
: Collections.emptySet();

return commentsPage.map(comment -> CommentMappers.toCommentResponse(
comment,
user,
userLikedComments.contains(comment.getId())
));
}

@Transactional
Expand All @@ -63,4 +83,14 @@ public void deleteComment(Long userId, Long commentId) {
comment.checkUser(userId);
commentRepository.delete(comment);
}

// 특정 사용자가 한 게시글 내 댓글에서 좋아요를 누른 댓글 ID 집합 조회
private Set<Long> getUserLikedComments(Long userId, Page<Comment> comments) {
Set<Long> commentIds = comments.getContent()
.stream()
.map(Comment::getId)
.collect(Collectors.toSet());

return commentLikeRepository.findLikedCommentsIdsByUserAndCommentIds(userId, commentIds);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,20 @@ public ResponseEntity<Void> removeLike(@PathVariable Long postId, @Authenticatio
likeService.removeLike(postId, cs.getUser().getId());
return ResponseEntity.ok(null);
}

@PostMapping("/{postId}/comments/{commentId}/likes")
public ResponseEntity<Void> addCommentLike(@PathVariable Long postId,
@PathVariable Long commentId,
@AuthenticationPrincipal CustomUserDetails cs) {
likeService.addCommentLike(cs.getUser().getId(), postId, commentId);
return ResponseEntity.status(HttpStatus.CREATED).body(null);
}

@DeleteMapping("/{postId}/comments/{commentId}/likes")
public ResponseEntity<Void> removeCommentLike(@PathVariable Long postId,
@PathVariable Long commentId,
@AuthenticationPrincipal CustomUserDetails cs) {
likeService.removeCommentLike(cs.getUser().getId(), postId, commentId);
return ResponseEntity.ok(null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,24 @@

import com.back.domain.like.entity.CommentLike;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Set;

/**
* 댓글 좋아요 엔티티에 대한 데이터베이스 접근을 담당하는 JpaRepository.
*/
@Repository
public interface CommentLikeRepository extends JpaRepository<CommentLike, Long> {
@Query("SELECT cl.comment.id FROM CommentLike cl WHERE cl.user.id = :userId AND cl.comment.id IN :commentIds")
Set<Long> findLikedCommentsIdsByUserAndCommentIds(@Param("userId") Long userId, @Param("commentIds") Set<Long> commentIds);

boolean existsByCommentIdAndUserId(Long commentId, Long userId);

@Modifying
@Query("DELETE FROM CommentLike cl WHERE cl.comment.id = :commentId AND cl.user.id = :userId")
int deleteByCommentIdAndUserId(@Param("commentId") Long commentId, @Param("userId") Long userId);
}
41 changes: 41 additions & 0 deletions back/src/main/java/com/back/domain/like/service/LikeService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.back.domain.like.service;

import com.back.domain.comment.entity.Comment;
import com.back.domain.comment.repository.CommentRepository;
import com.back.domain.like.entity.CommentLike;
import com.back.domain.like.entity.PostLike;
import com.back.domain.like.repository.CommentLikeRepository;
import com.back.domain.like.repository.PostLikeRepository;
Expand All @@ -23,6 +26,7 @@ public class LikeService {

private final PostLikeRepository postLikeRepository;
private final CommentLikeRepository commentLikeRepository;
private final CommentRepository commentRepository;
private final PostRepository postRepository;
private final UserRepository userRepository;

Expand Down Expand Up @@ -55,11 +59,48 @@ public void removeLike(Long postId, Long userId) {
post.decrementLikeCount();
}

@Transactional
public void addCommentLike(Long userId, Long postId, Long commentId) {
Comment comment = commentRepository.findByIdWithLock(commentId)
.orElseThrow(() -> new ApiException(ErrorCode.COMMENT_NOT_FOUND));

if (commentLikeRepository.existsByCommentIdAndUserId(commentId, userId)) {
throw new ApiException(ErrorCode.COMMENT_ALREADY_LIKED);
}

CommentLike commentLike = createCommentLike(comment, userId);

commentLikeRepository.save(commentLike);
comment.incrementLikeCount();
}

@Transactional
public void removeCommentLike(Long userId, Long postId, Long commentId) {
Comment comment = commentRepository.findByIdWithLock(commentId)
.orElseThrow(() -> new ApiException(ErrorCode.COMMENT_NOT_FOUND));

boolean deleted = commentLikeRepository.deleteByCommentIdAndUserId(commentId, userId) > 0;

if (!deleted) {
throw new ApiException(ErrorCode.LIKE_NOT_FOUND);
}

comment.decrementLikeCount();
}

private PostLike createPostLike(Post post, Long userId) {
User userReference = userRepository.getReferenceById(userId);
return PostLike.builder()
.post(post)
.user(userReference)
.build();
}

private CommentLike createCommentLike(Comment comment, Long userId) {
User userReference = userRepository.getReferenceById(userId);
return CommentLike.builder()
.comment(comment)
.user(userReference)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,13 @@ public PollOptionResponse fromPollOptionJson(String voteContent) {
throw new ApiException(ErrorCode.POLL_VOTE_INVALID_FORMAT);
}
}

public PollOptionResponse.VoteOption fromPollOptionInVoteOptionJson(String voteContent) {
if (voteContent == null) return null;
try {
return objectMapper.readValue(voteContent, PollOptionResponse.VoteOption.class);
} catch (JsonProcessingException e) {
throw new ApiException(ErrorCode.POLL_VOTE_INVALID_FORMAT);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* 투표 선택지 응답 DTO
*/
public record PollOptionResponse(
List<Integer> selected,
List<VoteOption> options
) {
public record VoteOption(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
* 투표 참여 엔티티에 대한 데이터베이스 접근을 담당하는 JpaRepository.
*/
@Repository
public interface PollVoteRepository extends JpaRepository<PollVote, Long> {
List<PollVote> findByPostId(@Param("postId") Long postId);

Optional<PollVote> findByPostIdAndUserId(Long userId, Long postId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ public ResponseEntity<PageResponse<PostSummaryResponse>> getPosts(
@Parameter(description = "검색 조건") @ModelAttribute PostSearchCondition condition,
@Parameter(description = "페이지 정보") Pageable pageable,
@AuthenticationPrincipal CustomUserDetails cs) {
Page<PostSummaryResponse> responses = postService.getPosts(cs.getUser().getId(), condition, pageable);
Long userId = (cs != null && cs.getUser() != null) ? cs.getUser().getId() : null;
Page<PostSummaryResponse> responses = postService.getPosts(userId, condition, pageable);
return ResponseEntity.ok(PageResponse.of(responses));
}

Expand All @@ -62,7 +63,8 @@ public ResponseEntity<PageResponse<PostSummaryResponse>> getPosts(
public ResponseEntity<PostDetailResponse> getPost(
@Parameter(description = "조회할 게시글 ID", required = true) @PathVariable Long postId,
@AuthenticationPrincipal CustomUserDetails cs) {
return ResponseEntity.ok(postService.getPost(cs.getUser().getId(), postId));
Long userId = (cs != null && cs.getUser() != null) ? cs.getUser().getId() : null;
return ResponseEntity.ok(postService.getPost(userId, postId));
}

@PutMapping("/{postId}")
Expand Down
15 changes: 10 additions & 5 deletions back/src/main/java/com/back/domain/post/entity/Post.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.back.domain.post.entity;

import com.back.domain.comment.entity.Comment;
import com.back.domain.poll.entity.PollVote;
import com.back.domain.post.enums.PostCategory;
import com.back.domain.scenario.entity.Scenario;
import com.back.domain.user.entity.User;
import com.back.global.baseentity.BaseEntity;
import com.back.global.exception.ApiException;
Expand All @@ -18,11 +20,6 @@
import java.util.ArrayList;
import java.util.List;

/**
* 게시글 엔티티.
* 사용자가 작성한 게시글의 정보를 저장합니다.
* 인덱스...
*/
@Entity
@Getter
@Table(name = "post",
Expand Down Expand Up @@ -69,6 +66,14 @@ public class Post extends BaseEntity {
@Builder.Default
private List<Comment> comments = new ArrayList<>();

@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
@Builder.Default
private List<PollVote> pollVotes = new ArrayList<>();

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "scenario_id")
private Scenario scenario;

public void updatePost(String title, String content, PostCategory category) {
this.title = title;
this.content = content;
Expand Down
Loading