-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommentService.java
More file actions
197 lines (170 loc) · 8.44 KB
/
CommentService.java
File metadata and controls
197 lines (170 loc) · 8.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package cc.backend.board.service;
import cc.backend.apiPayLoad.code.status.ErrorStatus;
import cc.backend.apiPayLoad.exception.GeneralException;
import cc.backend.board.dto.request.CommentRequest;
import cc.backend.board.dto.response.CommentCreateResponse;
import cc.backend.board.dto.response.CommentResponse;
import cc.backend.board.entity.Board;
import cc.backend.board.entity.Comment;
import cc.backend.board.entity.CommentLike;
import cc.backend.board.repository.BoardRepository;
import cc.backend.board.repository.CommentLikeRepository;
import cc.backend.board.repository.CommentRepository;
import cc.backend.notice.event.entity.CommentEvent;
import cc.backend.notice.event.entity.ReplyEvent;
import cc.backend.member.entity.Member;
import cc.backend.member.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class CommentService {
private final CommentRepository commentRepository;
private final CommentLikeRepository commentLikeRepository;
private final BoardRepository boardRepository;
private final MemberRepository memberRepository;
private final ApplicationEventPublisher eventPublisher; //이벤트 생성자
//댓글 작성
@Transactional
public CommentCreateResponse createComment(Long boardId, Long memberId, CommentRequest req) {
Board board = boardRepository.findById(boardId)
.orElseThrow(() -> new GeneralException(ErrorStatus.BOARD_NOT_FOUND));
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));
Comment comment;
if (req.getParentCommentId() == null) {
// 댓글
comment = Comment.createComment(req.getContent(), member, board);
commentRepository.save(comment);
eventPublisher.publishEvent(new CommentEvent(boardId, board.getMember().getId(), comment.getId(), comment.getMember().getId())); //댓글 이벤트 생성
} else {
// 대댓글
Comment parent = commentRepository.findById(req.getParentCommentId())
.orElseThrow(() -> new GeneralException(ErrorStatus.COMMENT_NOT_FOUND));
// 부모 댓글이 해당 게시글에 속한 댓글인지 확인
if (!parent.getBoard().getId().equals(boardId)) {
throw new GeneralException(ErrorStatus.COMMENT_BOARD_MISMATCH);
}
if (parent.getDepth() != 0) {
throw new GeneralException(ErrorStatus.COMMENT_DEPTH_EXCEEDED);
}
comment = Comment.createReply(req.getContent(), member, board, parent);
commentRepository.save(comment);
eventPublisher.publishEvent(new ReplyEvent(parent.getId(), parent.getMember().getId(), comment.getId(), comment.getMember().getId())); //대댓글 이벤트 생성
}
board.increaseCommentCount();
Long boardWriterId = board.getMember().getId();
return CommentCreateResponse.from(comment, boardWriterId);
}
//댓글/대댓글 수정
@Transactional
public CommentCreateResponse updateComment(Long memberId, Long commentId, String newContent) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new GeneralException(ErrorStatus.COMMENT_NOT_FOUND));
if (!comment.getMember().getId().equals(memberId)) {
throw new GeneralException(ErrorStatus.COMMENT_ACCESS_DENIED);
}
comment.updateContent(newContent);
// 게시글 작성자 id 추출
Long boardWriterId = comment.getBoard().getMember().getId();
return CommentCreateResponse.from(comment, boardWriterId);
}
// 댓글/대댓글 삭제
@Transactional
public void deleteComment(Long memberId, Long commentId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new GeneralException(ErrorStatus.COMMENT_NOT_FOUND));
if (!comment.getMember().getId().equals(memberId)) {
throw new GeneralException(ErrorStatus.COMMENT_ACCESS_DENIED);
}
commentRepository.delete(comment); // soft delete
Board board = comment.getBoard();
board.decreaseCommentCount();
}
// 댓글/대댓글 목록 조회
@Transactional(readOnly = true)
public List<CommentResponse> getComments(Long boardId,Long memberId) {
Board board = boardRepository.findById(boardId)
.orElseThrow(() -> new GeneralException(ErrorStatus.BOARD_NOT_FOUND));
List<Comment> comments = commentRepository.findByBoardOrderByCreatedAtAsc(board);
Long boardWriterId = board.getMember().getId();
List<Long> commentIds = comments.stream()
.map(Comment::getId)
.collect(Collectors.toList());
//현재 사용자가 좋아요 눌렀는지 여부 한 번에 조회
List<Long> likedCommentIds = commentLikeRepository.findLikedCommentIdsByMemberAndCommentIds(memberId, commentIds);
Set<Long> likedCommentIdSet = new HashSet<>(likedCommentIds);
// 모든 댓글을 Map<id, CommentResponse>로 변환
Map<Long, CommentResponse> map = new LinkedHashMap<>();
for (Comment comment : comments) {
boolean liked = likedCommentIdSet.contains(comment.getId());
map.put(comment.getId(), CommentResponse.from(comment, boardWriterId,liked));
}
// 트리 구조로 변환
List<CommentResponse> result = new ArrayList<>();
for (Comment comment : comments) {
CommentResponse response = map.get(comment.getId());
if (comment.getParent() == null) {
// 최상위 댓글
result.add(response);
} else {
// 대댓글을 부모의 children에 추가
CommentResponse parentResponse = map.get(comment.getParent().getId());
parentResponse.getChildren().add(response);
}
}
return result;
}
//댓글 좋아요
@Transactional
public int toggleCommentLike(Long commentId, Long memberId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new GeneralException(ErrorStatus.COMMENT_NOT_FOUND));
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));
Optional<CommentLike> existingLike = commentLikeRepository.findByMemberAndComment(member, comment);
if (existingLike.isPresent()) {
// 이미 좋아요한 경우: 취소
commentLikeRepository.delete(existingLike.get());
comment.decreaseLikeCount();
return -1;
} else {
// 좋아요 추가
CommentLike like = CommentLike.of(member, comment);
commentLikeRepository.save(like);
comment.increaseLikeCount();
return 1;
}
}
// 댓글/대댓글 목록 조회
@Transactional(readOnly = true)
public List<CommentResponse> getCommentsForAdmin(Long boardId) {
Board board = boardRepository.findById(boardId)
.orElseThrow(() -> new GeneralException(ErrorStatus.BOARD_NOT_FOUND));
List<Comment> comments = commentRepository.findByBoardOrderByCreatedAtAsc(board);
Long boardWriterId = board.getMember().getId();
// 모든 댓글을 Map<id, CommentResponse>로 변환
Map<Long, CommentResponse> map = new LinkedHashMap<>();
for (Comment comment : comments) {
map.put(comment.getId(), CommentResponse.fromForAdmin(comment, boardWriterId));
}
// 트리 구조로 변환
List<CommentResponse> result = new ArrayList<>();
for (Comment comment : comments) {
CommentResponse response = map.get(comment.getId());
if (comment.getParent() == null) {
// 최상위 댓글
result.add(response);
} else {
// 대댓글을 부모의 children에 추가
CommentResponse parentResponse = map.get(comment.getParent().getId());
parentResponse.getChildren().add(response);
}
}
return result;
}
}