Skip to content

Commit

Permalink
feat: 리액션 API 추가 및 추천리스트 API, 리스트 상세조회 API 재구현 (#304)
Browse files Browse the repository at this point in the history
* feat: 리액션 API 추가 및 추천리스트 API, 리스트 상세조회 API 재구현

* test: 리액션 관련 테스트 추가 및 이에 따른 변경된 API에 대한 테스트코드 수정

* refactor: 코드리뷰에 의한 네이밍 변경 및 리액션 패키지구조 별도 추출

* refactor: 코드리뷰에 의한 네이밍 변경
  • Loading branch information
pparkjs authored Oct 27, 2024
1 parent 308ed57 commit ef84178
Show file tree
Hide file tree
Showing 23 changed files with 653 additions and 183 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
public class AuthorizationInterceptor implements HandlerInterceptor {

private static final UriAndMethod[] whiteList = {
new UriAndMethod("/lists/explore", GET),
new UriAndMethod("/lists/recommended", GET),
new UriAndMethod("/lists/search", GET),
new UriAndMethod("/lists/{listId}/comments", GET),
new UriAndMethod("/lists/upload-url", GET),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,4 +266,8 @@ public void validateUpdateAuthority(User loginUser, Collaborators beforeCollabor
public void increaseUpdateCount() {
this.updateCount++;
}

public boolean isOwner(User loginUser) {
return this.user.equals(loginUser);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.listywave.list.application.domain.item.Item;
import com.listywave.list.application.domain.label.Label;
import com.listywave.list.application.domain.list.ListEntity;
import com.listywave.reaction.application.dto.response.ReactionResponse;
import com.listywave.user.application.domain.User;
import jakarta.annotation.Nullable;
import java.time.LocalDateTime;
Expand All @@ -29,20 +30,24 @@ public record ListDetailResponse(
boolean isPublic,
String backgroundPalette,
String backgroundColor,
int collectCount,
Integer collectCount,
int viewCount,
int updateCount,
long totalCommentCount,
@Nullable NewestComment newestComment
@Nullable NewestComment newestComment,
List<ReactionResponse> reactions
) {

public static ListDetailResponse of(
ListEntity list,
User owner,
boolean isOwner,
boolean isCollected,
List<Collaborator> collaborators,
long totalCommentCount,
Comment newestComment,
Long totalReplyCount
Long totalReplyCount,
List<ReactionResponse> reactions
) {
return ListDetailResponse.builder()
.categoryEngName(list.getCategory().name().toLowerCase())
Expand All @@ -61,10 +66,12 @@ public static ListDetailResponse of(
.isPublic(list.isPublic())
.backgroundColor(list.getBackgroundColor().name())
.backgroundPalette(list.getBackgroundPalette().name())
.collectCount(list.getCollectCount())
.collectCount(isOwner ? list.getCollectCount() : null)
.viewCount(list.getViewCount())
.updateCount(list.getUpdateCount())
.totalCommentCount(totalCommentCount)
.newestComment(NewestComment.of(newestComment, totalReplyCount))
.reactions(reactions)
.build();
}

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.listywave.list.application.dto.response;

import com.listywave.list.application.domain.item.Item;
import com.listywave.list.application.domain.list.ListEntity;
import lombok.Builder;

import java.util.List;

@Builder
public record RecommendedListResponse(
Long id,
Long ownerId,
String ownerNickname,
String title,
String itemImageUrl,
String category,
String backgroundColor,
List<Top3ItemResponse> items
) {
public static RecommendedListResponse of(ListEntity list) {
return RecommendedListResponse.builder()
.id(list.getId())
.ownerId(list.getUser().getId())
.ownerNickname(list.getUser().getNickname())
.title(list.getTitle().getValue())
.itemImageUrl(list.getRepresentImageUrl())
.category(list.getCategory().getViewName())
.backgroundColor(list.getBackgroundColor().name())
.items(Top3ItemResponse.toList(list.getTop3Items().getValues()))
.build();
}

@Builder
public record Top3ItemResponse(
Long id,
int rank,
String title
) {

public static List<Top3ItemResponse> toList(List<Item> items) {
return items.stream()
.map(Top3ItemResponse::of)
.toList();
}

public static Top3ItemResponse of(Item item) {
return Top3ItemResponse.builder()
.id(item.getId())
.rank(item.getRanking())
.title(item.getTitle().getValue())
.build();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
import com.listywave.list.application.dto.response.ListDetailResponse;
import com.listywave.list.application.dto.response.ListRecentResponse;
import com.listywave.list.application.dto.response.ListSearchResponse;
import com.listywave.list.application.dto.response.ListTrandingResponse;
import com.listywave.list.application.dto.response.RecommendedListResponse;
import com.listywave.list.presentation.dto.request.ItemCreateRequest;
import com.listywave.list.presentation.dto.request.ListCreateRequest;
import com.listywave.list.presentation.dto.request.ListUpdateRequest;
Expand All @@ -41,6 +41,8 @@
import com.listywave.list.repository.label.LabelRepository;
import com.listywave.list.repository.list.ListRepository;
import com.listywave.list.repository.reply.ReplyRepository;
import com.listywave.reaction.application.dto.response.ReactionResponse;
import com.listywave.reaction.application.service.ReactionService;
import com.listywave.user.application.domain.Follow;
import com.listywave.user.application.domain.User;
import com.listywave.user.application.dto.FindFeedListResponse;
Expand Down Expand Up @@ -75,6 +77,7 @@ public class ListService {
private final AlarmRepository alarmRepository;
private final CollaboratorService collaboratorService;
private final HistoryService historyService;
private final ReactionService reactionService;
private final ApplicationEventPublisher applicationEventPublisher;

public ListCreateResponse listCreate(ListCreateRequest request, Long loginUserId) {
Expand Down Expand Up @@ -134,21 +137,33 @@ public ListDetailResponse getListDetail(Long listId, Long loginUserId) {
list.validateOwnerIsNotDeleted();
List<Collaborator> collaborators = collaboratorService.findAllByList(list).collaborators();

boolean isCollected = false;
if (loginUserId != null) {
User user = userRepository.getById(loginUserId);
isCollected = collectionRepository.existsByListAndUserId(list, user.getId());
}
User user = getUserIfLoggedIn(loginUserId);
boolean isCollected = checkIsCollected(list, user);
boolean isOwner = checkIsOwner(list, user);

List<ReactionResponse> reactions = reactionService.createReactionResponses(list, user, isOwner);
long totalCommentCount = commentRepository.countCommentsByList(list);
Comment newestComment = commentRepository.findFirstByListOrderByCreatedDateDesc(list);
Long totalReplyCount = replyRepository.countByComment(newestComment);
return ListDetailResponse.of(list, list.getUser(), isCollected, collaborators, totalCommentCount, newestComment, totalReplyCount);
return ListDetailResponse.of(
list,
list.getUser(),
isOwner,
isCollected,
collaborators,
totalCommentCount,
newestComment,
totalReplyCount,
reactions
);
}

@Transactional(readOnly = true)
public List<ListTrandingResponse> fetchTrandingLists() {
return listRepository.fetchTrandingLists();
public List<RecommendedListResponse> getRecommendedLists() {
List<ListEntity> recommendedLists = listRepository.findRecommendedLists();
return recommendedLists.stream()
.map(RecommendedListResponse::of)
.toList();
}

public void deleteList(Long listId, Long loginUserId) {
Expand Down Expand Up @@ -312,4 +327,16 @@ public void changeVisibility(Long loginUserId, Long listId) {
list.validateOwner(user);
list.updateVisibility();
}

private User getUserIfLoggedIn(Long loginUserId) {
return (loginUserId != null) ? userRepository.getById(loginUserId) : null;
}

private boolean checkIsCollected(ListEntity list, User user) {
return (user != null) && collectionRepository.existsByListAndUserId(list, user.getId());
}

private boolean checkIsOwner(ListEntity list, User user) {
return (user != null) && list.isOwner(user);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import com.listywave.list.application.dto.response.ListDetailResponse;
import com.listywave.list.application.dto.response.ListRecentResponse;
import com.listywave.list.application.dto.response.ListSearchResponse;
import com.listywave.list.application.dto.response.ListTrandingResponse;
import com.listywave.list.application.dto.response.RecommendedListResponse;
import com.listywave.list.application.service.ListService;
import com.listywave.list.presentation.dto.request.ListCreateRequest;
import com.listywave.list.presentation.dto.request.ListUpdateRequest;
Expand Down Expand Up @@ -54,10 +54,10 @@ ResponseEntity<ListDetailResponse> getListDetail(
return ResponseEntity.ok(listDetailResponse);
}

@GetMapping("/lists/explore")
ResponseEntity<List<ListTrandingResponse>> fetchTrandingLists() {
List<ListTrandingResponse> trandingList = listService.fetchTrandingLists();
return ResponseEntity.ok().body(trandingList);
@GetMapping("/lists/recommended")
ResponseEntity<List<RecommendedListResponse>> getRecommendedLists() {
List<RecommendedListResponse> recommendedLists = listService.getRecommendedLists();
return ResponseEntity.ok().body(recommendedLists);
}

@DeleteMapping("/lists/{listId}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.listywave.list.application.domain.category.CategoryType;
import com.listywave.list.application.domain.list.ListEntity;
import com.listywave.list.application.dto.response.ListTrandingResponse;
import com.listywave.user.application.domain.User;
import java.time.LocalDateTime;
import java.util.List;
Expand All @@ -11,7 +10,7 @@

public interface CustomListRepository {

List<ListTrandingResponse> fetchTrandingLists();
List<ListEntity> findRecommendedLists();

Slice<ListEntity> getRecentLists(LocalDateTime cursorUpdatedDate, CategoryType category, Pageable pageable);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,21 @@
import static com.listywave.common.exception.ErrorCode.NOT_SUPPORT_FILTER_ARGUMENT_EXCEPTION;
import static com.listywave.common.util.PaginationUtils.checkEndPage;
import static com.listywave.list.application.domain.category.CategoryType.ENTIRE;
import static com.listywave.list.application.domain.comment.QComment.comment;
import static com.listywave.list.application.domain.item.QItem.item;
import static com.listywave.list.application.domain.list.QListEntity.listEntity;
import static com.listywave.list.application.domain.reply.QReply.reply;
import static com.listywave.reaction.application.domain.QReactionStats.reactionStats;
import static com.listywave.user.application.domain.QUser.user;
import static com.querydsl.jpa.JPAExpressions.select;

import com.listywave.common.exception.CustomException;
import com.listywave.list.application.domain.category.CategoryType;
import com.listywave.list.application.domain.list.ListEntity;
import com.listywave.list.application.dto.response.ListTrandingResponse;
import com.listywave.list.repository.list.custom.CustomListRepository;
import com.listywave.user.application.domain.User;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
Expand All @@ -36,64 +29,39 @@ public class CustomListRepositoryImpl implements CustomListRepository {

private final JPAQueryFactory queryFactory;

@Override
public List<ListTrandingResponse> fetchTrandingLists() {
List<ListTrandingResponse> responses = getTrandingResponses();
return responses.stream()
.map(t -> t.with(getRepresentImageUrl(t.id())))
.collect(Collectors.toList());
public List<ListEntity> findRecommendedLists() {
List<Long> recommendedListIds = findRecommendedListIds();
return findRecommendedListsByIds(recommendedListIds);
}

private List<ListTrandingResponse> getTrandingResponses() {
public List<Long> findRecommendedListIds() {
LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
NumberPath<Long> trandingScoreAlias = Expressions.numberPath(Long.class, "trandingScore");

return queryFactory
.select(Projections.constructor(ListTrandingResponse.class,
listEntity.id.as("id"),
listEntity.user.id.as("ownerId"),
listEntity.user.nickname.value.as("ownerNickname"),
listEntity.user.profileImageUrl.value.as("ownerProfileImageUrl"),
listEntity.title.value.as("title"),
listEntity.description.value.as("description"),
listEntity.backgroundColor.as("backgroundColor"),
ExpressionUtils.as(
select(
listEntity.collectCount.multiply(3).add(
comment.countDistinct().add(reply.count()).multiply(2)
).castToNum(Long.class)
)
.from(comment)
.leftJoin(reply).on(reply.comment.id.eq(comment.id))
.where(comment.list.id.eq(listEntity.id)), trandingScoreAlias))
)
.from(listEntity)
.select(reactionStats.list.id)
.from(reactionStats)
.join(reactionStats.list, listEntity)
.join(listEntity.user, user)
.where(
listEntity.updatedDate.goe(thirtyDaysAgo),
reactionStats.updatedDate.goe(thirtyDaysAgo),
listEntity.isPublic.eq(true),
listEntity.user.isDelete.eq(false)
)
.distinct()
.orderBy(trandingScoreAlias.desc())
.groupBy(reactionStats.list.id)
.orderBy(reactionStats.count.sum().desc(), listEntity.updatedDate.desc())
.limit(10)
.fetch();
}

private String getRepresentImageUrl(Long id) {
String imageUrl = queryFactory
.select(item.imageUrl.value)
.from(item)
.where(
item.list.id.eq(id).and(
item.imageUrl.value.ne("")
)
)
.orderBy(item.ranking.asc())
.limit(1)
.fetchOne();
public List<ListEntity> findRecommendedListsByIds(List<Long> listIds) {
List<ListEntity> recommendedLists = queryFactory
.selectFrom(listEntity)
.join(listEntity.user, user).fetchJoin()
.leftJoin(item).on(listEntity.id.eq(item.list.id))
.where(listEntity.id.in(listIds))
.fetch();

return imageUrl != null ? imageUrl : "";
recommendedLists.sort(Comparator.comparingInt(o -> listIds.indexOf(o.getId())));
return recommendedLists;
}

@Override
Expand Down
Loading

0 comments on commit ef84178

Please sign in to comment.