Skip to content

Commit

Permalink
KKUMI-118 [FEATURE] #73 현재 유저가 좋아요 누른 상태인지 내려줌
Browse files Browse the repository at this point in the history
무한 스크롤 중, 현재 유저가 좋아요 누른 상태인지 확인하여 내려주는 코드 추가
likedByCurrentUser에 true, false로 제공함
  • Loading branch information
eekrwl committed Nov 9, 2024
1 parent b3e6541 commit d840638
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,20 @@
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;

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

public interface LikesRepository extends JpaRepository<Likes, Long> {

@Lock(LockModeType.OPTIMISTIC)
@Query("SELECT l from Likes l WHERE l.post = :post AND l.user = :user")
Optional<Likes> findByPostAndUser(Post post, User user); //TODO postid, userid로 하는게 나을지???

@Query(value = "SELECT p.post_id AS postId, " +
" CASE WHEN l.user_id = :userId AND l.is_deleted = false THEN true ELSE false END AS isLiked " +
"FROM post p " +
"LEFT JOIN likes l ON p.post_id = l.post_id AND l.user_id = :userId " +
"WHERE p.post_id IN :postIds", nativeQuery = true)
List<Map<String, Object>> findPostLikesStatus(List<Long> postIds, Long userId);
}
22 changes: 18 additions & 4 deletions src/main/java/com/swmarastro/mykkumiserver/like/LikesService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,29 @@

import com.swmarastro.mykkumiserver.global.exception.CommonException;
import com.swmarastro.mykkumiserver.global.exception.ErrorCode;
import com.swmarastro.mykkumiserver.post.PostRepository;
import com.swmarastro.mykkumiserver.post.domain.Post;
import com.swmarastro.mykkumiserver.post.service.PostService;
import com.swmarastro.mykkumiserver.user.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@RequiredArgsConstructor
@Transactional
public class LikesService {

private final LikesRepository likeRepository;
private final PostService postService;
private final PostRepository postRepository;

public Boolean like(User user, Long postId) {

Post post = postService.findById(postId);
Post post = postRepository.findById(postId).orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND, "해당 포스트가 존재하지 않습니다.", "해당 포스트가 존재하지 않습니다."));

//like가 테이블에 있는지 확인
Optional<Likes> optionalLike = likeRepository.findByPostAndUser(post, user);
Expand All @@ -41,7 +44,7 @@ public Boolean like(User user, Long postId) {
}

public Boolean unlike(User user, Long postId) {
Post post = postService.findById(postId);
Post post = postRepository.findById(postId).orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND, "해당 포스트가 존재하지 않습니다.", "해당 포스트가 존재하지 않습니다."));

//like가 테이블에 있는지 확인
Optional<Likes> optionalLike = likeRepository.findByPostAndUser(post, user);
Expand All @@ -59,4 +62,15 @@ public Boolean unlike(User user, Long postId) {
//TODO 좋아요가 이미 취소된 상태 -> 그냥 success 보내고 가만히 있으면 되지않나
}

public List<Boolean> isLikedByUser(User user, List<Long> postIds) {
List<Map<String, Object>> results = likeRepository.findPostLikesStatus(postIds, user.getId());
Map<Long, Boolean> likeStatusMap = results.stream()
.collect(Collectors.toMap(
result -> ((Number) result.get("postId")).longValue(),
result -> ((Number) result.get("isLiked")).intValue() == 1 // 변환 로직 추가
));
return postIds.stream()
.map(postId -> likeStatusMap.getOrDefault(postId, false))
.collect(Collectors.toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ public class PostDto {
private String category;
private String subCategory;
private Writer writer;
private Long likeCount;
private Boolean likedByCurrentUser;
private List<PostContentObject> content;
private List<PostImageDto> images;

Expand Down Expand Up @@ -52,4 +54,8 @@ public static PostDto of(PostView postView) {
.build();
}

public void updateLikedNByCurrentUser(Boolean likedByCurrentUser) {
this.likedByCurrentUser = likedByCurrentUser;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.swmarastro.mykkumiserver.global.exception.ErrorCode;
import com.swmarastro.mykkumiserver.global.util.Base64Utils;
import com.swmarastro.mykkumiserver.hashtag.*;
import com.swmarastro.mykkumiserver.like.LikesService;
import com.swmarastro.mykkumiserver.post.PostLatestCursor;
import com.swmarastro.mykkumiserver.post.PostMongoRepository;
import com.swmarastro.mykkumiserver.post.PostRepository;
Expand Down Expand Up @@ -45,6 +46,7 @@ public class PostService {
private final HashtagService hashtagService;
private final PostMongoRepository postMongoRepository;
private final ApplicationEventPublisher eventPublisher;
private final LikesService likesService;

public PostListResponse getInfiniteScrollPosts(User user, String encodedCursor, Integer limit) {
if (limit <= 0 || limit > 10)
Expand All @@ -65,11 +67,28 @@ public PostListResponse getInfiniteScrollPosts(User user, String encodedCursor,
return PostListResponse.end(posts);
}
posts.removeLast();

setLikes(posts, user); //좋아요 눌렀는지 세팅

Long lastId = getLastIdFromPostList(posts);
PostLatestCursor nextCursor = PostLatestCursor.of(cursor.getStartedAt(), lastId);
return PostListResponse.of(posts, Base64Utils.encode(nextCursor));
}

private void setLikes(List<PostDto> posts, User user) {
if (user == null) {
for (PostDto post : posts) {
post.updateLikedNByCurrentUser(false);
}
return;
}
List<Long> postIds = extractPostIds(posts);
List<Boolean> likedByUser = likesService.isLikedByUser(user, postIds);
for (int i = 0; i < posts.size(); i++) {
posts.get(i).updateLikedNByCurrentUser(likedByUser.get(i));
}
}

public Long registerPost(User user, Long subCategoryId, String content, List<PostImageDto> images) {

if (subCategoryId == null) {
Expand Down Expand Up @@ -185,4 +204,11 @@ public Post findById(Long postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND, "포스트가 존재하지 않습니다.", "포스트가 존재하지 않습니다."));
}

private List<Long> extractPostIds(List<PostDto> posts) {
return posts.stream()
.map(PostDto::getId)
.collect(Collectors.toList());
}

}

0 comments on commit d840638

Please sign in to comment.