Skip to content

Commit 418a137

Browse files
limdododjunsoo22
andauthored
feat: newVote 댓글에 반영 (#100)
* fix: voteType 업데이트 수정 * refractor: 메서드 분리 * fix:voteType DB 반영 * merge 해결 * fix: newsVoteType 댓글에 반영&수정 시 update * fix: voteNum 반영(@transactional) 추가) --------- Co-authored-by: kim junsoo <kjs201105@naver.com>
1 parent dbd4e15 commit 418a137

6 files changed

Lines changed: 48 additions & 28 deletions

File tree

src/main/java/com/tave/alarmissue/news/controller/NewsCommentController.java

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,23 @@ public class NewsCommentController {
2828

2929
@PostMapping
3030
@Operation(summary = "댓글 작성", description = "특정 뉴스에 댓글 작성합니다.")
31-
public ResponseEntity<NewsCommentResponseDto> createComment(@RequestBody NewsCommentRequestDto dto,
32-
@AuthenticationPrincipal PrincipalUserDetails principal) {
31+
public ResponseEntity<NewsCommentResponseDto> createComment(@RequestBody NewsCommentRequestDto dto, @AuthenticationPrincipal PrincipalUserDetails principal) {
3332
Long userId = principal.getUserId();
34-
3533
NewsCommentResponseDto responseDto = newsCommentService.createComment(dto,userId, dto.getNewsId());
36-
return ResponseEntity.status(HttpStatus.OK).body(responseDto);
34+
return ResponseEntity.status(HttpStatus.CREATED).body(responseDto);
3735
}
3836

3937
@GetMapping("/{newsId}")
40-
@Operation(summary = "댓글 목록 조회(답글 포함)", description = "특정 뉴스의 모든 댓글을 최신순으로 조회합니다.(답글 포함)")
41-
public ResponseEntity<NewsCommentListResponseDto> getComments(@PathVariable Long newsId){
38+
@Operation(summary = "댓글 목록 조회", description = "특정 뉴스의 모든 댓글을 최신순으로 조회합니다.")
39+
public ResponseEntity<NewsCommentListResponseDto> getComments(@PathVariable Long newsId, @AuthenticationPrincipal PrincipalUserDetails principal) {
40+
41+
Long userId = null;
42+
if (principal != null) {
43+
userId = principal.getUserId();
44+
}
4245

43-
NewsCommentListResponseDto comments = newsCommentService.getCommentsByNewsId(newsId);
44-
return ResponseEntity.status(HttpStatus.OK).body(comments);
46+
NewsCommentListResponseDto comments=newsCommentService.getCommentsByNewsId(newsId,userId);
47+
return ResponseEntity.ok(comments);
4548
}
4649

4750
@DeleteMapping("/{commentId}")

src/main/java/com/tave/alarmissue/news/converter/NewsCommentConverter.java

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
import com.tave.alarmissue.news.dto.request.NewsReplyRequest;
99
import com.tave.alarmissue.news.dto.response.NewsCommentListResponseDto;
1010
import com.tave.alarmissue.news.dto.response.NewsCommentResponseDto;
11+
import com.tave.alarmissue.news.dto.response.NewsVoteResponseDto;
12+
import com.tave.alarmissue.news.repository.NewsVoteRepository;
1113
import com.tave.alarmissue.news.util.TimeAgoUtil;
1214
import com.tave.alarmissue.user.domain.UserEntity;
1315
import org.springframework.stereotype.Component;
@@ -19,15 +21,16 @@
1921
@Component
2022
public class NewsCommentConverter {
2123
//답글용
22-
public static NewsCommentResponseDto toCommentResponseDto(NewsComment newsComment){
24+
public static NewsCommentResponseDto toCommentResponseDto(NewsComment newsComment, NewsVoteType currentUserVoteType){
2325
return NewsCommentResponseDto.builder()
2426
.commentId(newsComment.getId())
2527
.comment(newsComment.getComment())
2628
.nickName(newsComment.getUser().getNickName())
2729
.createdAt(newsComment.getCreatedAt())
2830
.timeAgo(TimeAgoUtil.getTimeAgo(newsComment.getCreatedAt())) //현재 시간과 계산한 값
2931
.parentId(newsComment.getParentComment()!=null ? newsComment.getParentComment().getId():null)
30-
.voteType(newsComment.getVoteType() != null ? newsComment.getVoteType() : null)
32+
// .voteType(newsComment.getVoteType() != null ? newsComment.getVoteType() : null)
33+
.voteType(currentUserVoteType)
3134
.build();
3235
}
3336

@@ -41,9 +44,10 @@ public NewsComment toComment(NewsCommentRequestDto dto, UserEntity user, News ne
4144

4245
}
4346

44-
public static NewsCommentListResponseDto toCommentListResponseDto(Long newsId, Long totalCount, List<NewsComment> comments) {
47+
public static NewsCommentListResponseDto toCommentListResponseDto(Long newsId, Long totalCount, List<NewsComment> comments,NewsVoteType currentUserVoteType) {
4548
List<NewsCommentResponseDto> commentResponseDtos = comments.stream()
46-
.map(NewsCommentConverter::toCommentWithRepliesDto)
49+
// .map(NewsCommentConverter::toCommentWithRepliesDto)
50+
.map(comment->toCommentWithRepliesDto(comment,currentUserVoteType))
4751
.collect(Collectors.toList());
4852

4953
return NewsCommentListResponseDto.builder()
@@ -54,11 +58,12 @@ public static NewsCommentListResponseDto toCommentListResponseDto(Long newsId, L
5458
}
5559

5660
// 답글 포함 댓글 변환
57-
public static NewsCommentResponseDto toCommentWithRepliesDto(NewsComment newsComment) {
61+
public static NewsCommentResponseDto toCommentWithRepliesDto(NewsComment newsComment,NewsVoteType currentUserVoteType) {
5862
// 답글들을 DTO로 변환
5963
List<NewsCommentResponseDto> replyDtos = newsComment.getReplies().stream()
6064
.sorted((r1, r2) -> r1.getCreatedAt().compareTo(r2.getCreatedAt())) // 답글은 오래된 순
61-
.map(NewsCommentConverter::toCommentResponseDto)
65+
// .map(NewsCommentConverter::toCommentResponseDto)
66+
.map(reply->toCommentResponseDto(reply,currentUserVoteType))
6267
.collect(Collectors.toList());
6368

6469
return NewsCommentResponseDto.builder()
@@ -67,11 +72,12 @@ public static NewsCommentResponseDto toCommentWithRepliesDto(NewsComment newsCom
6772
.nickName(newsComment.getUser().getNickName())
6873
.createdAt(newsComment.getCreatedAt())
6974
.timeAgo(TimeAgoUtil.getTimeAgo(newsComment.getCreatedAt()))
70-
.voteType(newsComment.getVoteType())
75+
// .voteType(newsComment.getVoteType())
76+
.voteType(currentUserVoteType)
7177
.parentId(null) // 원댓글이므로 null
7278
.replies(replyDtos) // 답글들 포함
7379
.replyCount(replyDtos.size())
7480
.build();
7581
}
7682

77-
}
83+
}

src/main/java/com/tave/alarmissue/news/repository/NewsCommentRepository.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,6 @@ public interface NewsCommentRepository extends JpaRepository<NewsComment,Long> {
2424
List<NewsComment> findByNewsIdAndParentCommentIsNullOrderByCreatedAtDesc(Long newsId); // 원댓글만 조회
2525
List<NewsComment> findByParentCommentIdOrderByCreatedAtDesc(Long parentCommentId); // 특정 댓글의 답글들
2626
Long countByParentCommentId(Long parentCommentId);
27+
28+
List<NewsComment> findByNewsIdAndUserId(Long newsId, Long userId);
2729
}

src/main/java/com/tave/alarmissue/news/repository/NewsVoteRepository.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
import org.springframework.data.repository.query.Param;
1212

1313
import java.util.List;
14+
import java.util.Map;
1415
import java.util.Optional;
16+
import java.util.Set;
1517

1618

1719
public interface NewsVoteRepository extends JpaRepository<NewsVote, Long> {
@@ -24,8 +26,8 @@ public interface NewsVoteRepository extends JpaRepository<NewsVote, Long> {
2426
@Query("SELECT v.voteType, COUNT(v) FROM NewsVote v WHERE v.news = :news GROUP BY v.voteType")
2527
List<NewsVoteCountResponse> countVotesByType(@Param("news") News news);
2628

27-
@Query("SELECT nv FROM NewsVote nv WHERE nv.news.id = :newsId AND nv.user.id IN :userIds")
28-
List<NewsVote> findVoteTypesByNewsIdAndUserIds(@Param("newsId") Long newsId, @Param("userIds") List<Long> userIds);
29+
@Query("SELECT v FROM NewsVote v WHERE v.news.id = :newsId AND v.user.id IN :userIds")
30+
List<NewsVote> findByNewsIdAndUserIds(@Param("newsId") Long newsId, @Param("userIds") Set<Long> userIds);
2931

3032
Optional<NewsVote> findByNewsAndUser(News news, UserEntity user);
3133

@@ -35,5 +37,4 @@ int updateVoteTypeByNewsIdAndUserId(@Param("voteType") NewsVoteType voteType,
3537
@Param("newsId") Long newsId,
3638
@Param("userId") Long userId);
3739

38-
3940
}

src/main/java/com/tave/alarmissue/news/service/NewsCommentService.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,13 @@
1313
import com.tave.alarmissue.news.repository.NewsCommentRepository;
1414
import com.tave.alarmissue.news.repository.NewsRepository;
1515
import com.tave.alarmissue.news.repository.NewsVoteRepository;
16-
import com.tave.alarmissue.post.domain.Post;
17-
import com.tave.alarmissue.post.exception.PostException;
1816
import com.tave.alarmissue.user.domain.UserEntity;
1917
import com.tave.alarmissue.user.repository.UserRepository;
2018
import lombok.RequiredArgsConstructor;
2119
import org.springframework.stereotype.Service;
2220
import org.springframework.transaction.annotation.Transactional;
2321

2422
import java.util.List;
25-
import java.util.stream.Collectors;
2623

2724
import static com.tave.alarmissue.news.exceptions.NewsErrorCode.*;
2825

@@ -52,18 +49,19 @@ public NewsCommentResponseDto createComment(NewsCommentRequestDto dto, Long user
5249
NewsComment saved = newsCommentRepository.save(newsComment);
5350
news.incrementCommentCount();
5451

55-
return NewsCommentConverter.toCommentResponseDto(saved);
52+
return NewsCommentConverter.toCommentResponseDto(saved,newsVoteType);
5653
}
5754

5855
// 뉴스 댓글 반환
59-
public NewsCommentListResponseDto getCommentsByNewsId(Long newsId) {
56+
public NewsCommentListResponseDto getCommentsByNewsId(Long newsId, Long userId) {
6057

6158
List<NewsComment> comments = newsCommentRepository.findByNewsIdAndParentCommentIsNullOrderByCreatedAtDesc(newsId);
6259
News news = getNewsById(newsId);
6360

6461
Long totalCount = news.getCommentNum();
62+
NewsVoteType currentUserVoteType = newsVoteRepository.findVoteTypeByNewsIdAndUserId(newsId, userId).orElse(null);
6563

66-
return NewsCommentConverter.toCommentListResponseDto(newsId, totalCount, comments);
64+
return NewsCommentConverter.toCommentListResponseDto(newsId, totalCount, comments,currentUserVoteType);
6765
}
6866

6967

@@ -97,8 +95,9 @@ public NewsCommentResponseDto updateComment(Long commentId, Long userId, NewsCom
9795

9896
//댓글 내용 업데이트
9997
comment.updateContent(dto.getComment().trim());
98+
NewsVoteType currentUserVoteType=newsVoteRepository.findVoteTypeByNewsIdAndUserId(comment.getNews().getId(),userId).orElse(null);
10099

101-
return NewsCommentConverter.toCommentResponseDto(comment);
100+
return NewsCommentConverter.toCommentResponseDto(comment,currentUserVoteType);
102101

103102
}
104103

@@ -127,7 +126,7 @@ public NewsCommentResponseDto createReply(Long userId, NewsReplyRequest dto) {
127126

128127
news.incrementCommentCount();
129128

130-
return NewsCommentConverter.toCommentResponseDto(savedReply);
129+
return NewsCommentConverter.toCommentResponseDto(savedReply,newsVoteType);
131130
}
132131

133132

src/main/java/com/tave/alarmissue/news/service/NewsVoteService.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ public class NewsVoteService {
3232
private final NewsVoteRepository newsVoteRepository;
3333
private final NewsRepository newsRepository;
3434
private final UserRepository userRepository;
35+
private final NewsCommentRepository newsCommentRepository;
3536

3637
@Transactional
3738
public void createVoteAndGetResult(NewsVoteRequestDto dto, Long userId) {
@@ -59,10 +60,12 @@ public void createVoteAndGetResult(NewsVoteRequestDto dto, Long userId) {
5960
newsVoteRepository.save(vote);
6061

6162
//DB에 update
62-
updateVoteType(dto.getNewsId(),userId, dto.getVoteType());
63+
// updateVoteType(dto.getNewsId(),userId, dto.getVoteType());
64+
updateCommentsVoteType(dto.getNewsId(),userId, dto.getVoteType());
6365

6466
}
6567

68+
@Transactional
6669
public NewsVoteResponseDto getVoteResult(NewsVoteRequestDto dto, Long userId) {
6770

6871
News news = getNews(dto.getNewsId());
@@ -77,6 +80,12 @@ public NewsVoteResponseDto getVoteResult(NewsVoteRequestDto dto, Long userId) {
7780
return NewsVoteConverter.toVoteResponseDto(news, vote.getVoteType(), voteCounts);
7881
}
7982

83+
private void updateCommentsVoteType(Long newsId, Long userId, NewsVoteType voteType) {
84+
// 모든 댓글을 조회해서 업데이트
85+
List<NewsComment> userComments = newsCommentRepository.findByNewsIdAndUserId(newsId, userId);
86+
userComments.forEach(comment -> comment.updateVoteType(voteType));
87+
}
88+
8089
/*
8190
private method 분리
8291
*/

0 commit comments

Comments
 (0)