Skip to content

Commit

Permalink
Merge pull request #164 from side-peek/fix/#153-update-comment-count
Browse files Browse the repository at this point in the history
댓글 생성 및 삭제 시 댓글 수 업데이트 안 되는 버그 해결
  • Loading branch information
Sehee-Lee-01 authored Mar 14, 2024
2 parents ee80972 + fca2ebe commit 2524aba
Show file tree
Hide file tree
Showing 12 changed files with 134 additions and 127 deletions.
4 changes: 4 additions & 0 deletions config/checkstyle/suppressions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@
<!-- DOC 패키지 하위에 대한 LineLength 검사를 무시 -->
<suppress checks="LineLength"
files="[\\/]common[\\/]doc[\\/]"/>

<!-- TEST 패키지 하위에 대한 VariableDeclarationUsageDistance 검사를 무시 -->
<suppress checks="VariableDeclarationUsageDistance"
files=".*src[/\\]test[/\\].*\.java"/>
</suppressions>
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import sixgaezzang.sidepeek.comments.dto.request.UpdateCommentRequest;
import sixgaezzang.sidepeek.common.domain.BaseTimeEntity;
import sixgaezzang.sidepeek.projects.domain.Project;
Expand All @@ -45,7 +47,7 @@ public class Comment extends BaseTimeEntity {
@JoinColumn(name = "user_id")
private User user;

// TODO: @OnDelete(action = OnDeleteAction.CASCADE) 설정을 안해도 돌아간다. 필요할까!(고민중)
@OnDelete(action = OnDeleteAction.CASCADE)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Comment parent;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ public interface CommentRepositoryCustom {

List<Comment> findAllReplies(Comment parent);

long countRepliesByParent(Comment parent);

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,13 @@ public List<Comment> findAllReplies(Comment parent) {
.where(comment.parent.eq(parent))
.fetch();
}

@Override
public long countRepliesByParent(Comment parent) {
return queryFactory
.select(comment.count())
.from(comment)
.where(comment.parent.eq(parent))
.fetchOne();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,13 @@
import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sixgaezzang.sidepeek.comments.domain.Comment;
import sixgaezzang.sidepeek.comments.dto.request.SaveCommentRequest;
import sixgaezzang.sidepeek.comments.dto.request.UpdateCommentRequest;
import sixgaezzang.sidepeek.comments.dto.response.CommentResponse;
import sixgaezzang.sidepeek.comments.dto.response.CommentWithCountResponse;
import sixgaezzang.sidepeek.comments.dto.response.ReplyResponse;
import sixgaezzang.sidepeek.comments.repository.CommentRepository;
import sixgaezzang.sidepeek.projects.domain.Project;
Expand Down Expand Up @@ -60,6 +58,8 @@ public Long save(Long loginId, SaveCommentRequest request) {
Comment comment = request.toEntity(project, parent, owner);
commentRepository.save(comment);

project.increaseCommentCount(); // 댓글 수 증가

return comment.getProject().getId();
}

Expand All @@ -68,22 +68,16 @@ public Comment getById(Long id, String message) {
.orElseThrow(() -> new EntityNotFoundException(message));
}

public CommentWithCountResponse findAll(Project project) {
public List<CommentResponse> findAll(Project project) {
List<Comment> comments = commentRepository.findAll(project);
AtomicLong commentCount = new AtomicLong((long) comments.size()); // 댓글 개수

List<CommentResponse> results = comments.stream()
return comments.stream()
.map(comment -> {
boolean isOwner = isSameOwner(comment, project);
List<ReplyResponse> replies = mapReplies(comment);
if (Objects.nonNull(replies)) {
commentCount.addAndGet(replies.size()); // 대댓글 개수 추가
}
return CommentResponse.from(comment, isOwner, replies);
})
.toList();

return CommentWithCountResponse.from(results, commentCount.get());
}

@Transactional
Expand All @@ -105,6 +99,9 @@ public void delete(Long loginId, Long commentId) {
Comment comment = getById(commentId, COMMENT_NOT_EXISTING);

validateLoginIdEqualsOwnerId(loginId, comment.getOwnerId());

decreaseAllCommentCount(comment); // 댓글 수 감소

commentRepository.delete(comment);
}

Expand All @@ -123,4 +120,11 @@ private List<ReplyResponse> mapReplies(Comment comment) {
.toList();
}

private void decreaseAllCommentCount(Comment comment) { // 댓글 삭제 시 대댓글도 삭제하기 위한 메서드
Project project = comment.getProject();

long replyCount = commentRepository.countRepliesByParent(comment); // 대댓글 수 가져오기
project.decreaseCommentCount(replyCount + 1); // 대댓글 수 + 댓글 수(1) 감소
}

}
12 changes: 12 additions & 0 deletions src/main/java/sixgaezzang/sidepeek/projects/domain/Project.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ public class Project extends BaseTimeEntity {
@Column(name = "view_count", nullable = false)
private Long viewCount;

@Column(name = "comment_count", nullable = false)
private Long commentCount;

@Column(name = "deleted_at")
private LocalDateTime deletedAt;

Expand Down Expand Up @@ -116,6 +119,7 @@ public Project(String name, String subName, String overview, YearMonth startDate
// Etc
this.likeCount = 0L;
this.viewCount = 0L;
this.commentCount = 0L;
}

public void increaseViewCount() {
Expand All @@ -130,6 +134,14 @@ public void decreaseLikeCount() {
this.likeCount--;
}

public void increaseCommentCount() {
this.commentCount++;
}

public void decreaseCommentCount(long commentCount) {
this.commentCount -= commentCount;
}

public void softDelete(LocalDateTime now) {
if (Objects.isNull(this.deletedAt)) {
this.deletedAt = now;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import java.util.List;
import lombok.Builder;
import sixgaezzang.sidepeek.comments.dto.response.CommentResponse;
import sixgaezzang.sidepeek.comments.dto.response.CommentWithCountResponse;
import sixgaezzang.sidepeek.projects.domain.Project;

@Schema(description = "프로젝트 상세 조회 응답")
Expand Down Expand Up @@ -60,13 +59,13 @@ public static ProjectResponse from(Project project, List<OverviewImageSummary> o
overviewImageUrl,
techStacks,
members,
new CommentWithCountResponse(Collections.emptyList(), 0L)
Collections.emptyList()
);
}

public static ProjectResponse from(Project project, List<OverviewImageSummary> overviewImageUrl,
List<ProjectSkillSummary> techStacks, List<MemberSummary> members,
CommentWithCountResponse comments
List<CommentResponse> comments
) {
return ProjectResponse.builder()
.id(project.getId())
Expand All @@ -79,15 +78,15 @@ public static ProjectResponse from(Project project, List<OverviewImageSummary> o
.deployUrl(project.getDeployUrl())
.viewCount(project.getViewCount())
.likeCount(project.getLikeCount())
.commentCount(comments.commentCount()) // 댓글 + 대댓글
.commentCount(project.getCommentCount()) // 댓글 + 대댓글
.techStacks(techStacks)
.ownerId(project.getOwnerId())
.startDate(project.getStartDate())
.endDate(project.getEndDate())
.members(members)
.description(project.getDescription())
.troubleShooting(project.getTroubleshooting())
.comments(comments.results())
.comments(comments)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sixgaezzang.sidepeek.comments.dto.response.CommentWithCountResponse;
import sixgaezzang.sidepeek.comments.dto.response.CommentResponse;
import sixgaezzang.sidepeek.comments.service.CommentService;
import sixgaezzang.sidepeek.common.dto.request.SaveTechStackRequest;
import sixgaezzang.sidepeek.common.dto.response.Page;
Expand Down Expand Up @@ -106,7 +106,7 @@ public ProjectResponse findById(Long id) {

List<MemberSummary> members = memberService.findAllWithUser(project);

CommentWithCountResponse comments = commentService.findAll(project);
List<CommentResponse> comments = commentService.findAll(project);

return ProjectResponse.from(project, overviewImages, techStacks, members, comments);
}
Expand All @@ -120,7 +120,7 @@ public List<ProjectBannerResponse> findAllPopularLastWeek() {
}

public Page<ProjectListResponse> findByUser(Long userId, Long loginId,
UserProjectSearchType type, Pageable pageable) {
UserProjectSearchType type, Pageable pageable) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException(USER_NOT_EXISTING));

Expand Down Expand Up @@ -176,19 +176,19 @@ private List<Long> getLikedProjectIds(Long userId) {
}

private Page<ProjectListResponse> findJoinedProjectsByUser(User user,
List<Long> likedProjectIds,
Pageable pageable) {
List<Long> likedProjectIds,
Pageable pageable) {
return Page.from(projectRepository.findAllByUserJoined(likedProjectIds, user, pageable));
}

private Page<ProjectListResponse> findLikedProjectsByUser(User user, List<Long> likedProjectIds,
Pageable pageable) {
Pageable pageable) {
return Page.from(projectRepository.findAllByUserLiked(likedProjectIds, user, pageable));
}

private Page<ProjectListResponse> findAllByUserCommentedByUser(User user,
List<Long> likedProjectIds,
Pageable pageable) {
List<Long> likedProjectIds,
Pageable pageable) {
return Page.from(projectRepository.findAllByUserCommented(likedProjectIds, user, pageable));
}

Expand Down
Loading

0 comments on commit 2524aba

Please sign in to comment.