Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] 인기 있는 토론방 조회 API 및 최근 의견이 달린 토론방 API 구현 #85

Merged
merged 4 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/docs/asciidoc/api/comment/comment.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ include::{snippets}/comment/create/request-fields.adoc[]
include::{snippets}/comment/create/http-response.adoc[]
include::{snippets}/comment/create/response-fields.adoc[]

=== 의견 조회

==== HTTP Request

include::{snippets}/comment/find/http-request.adoc[]
include::{snippets}/comment/find/path-parameters.adoc[]

==== HTTP Response

include::{snippets}/comment/find/http-response.adoc[]
include::{snippets}/comment/find/response-fields.adoc[]

=== 의견 수정

==== HTTP Request
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/com/jisungin/api/SearchRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class SearchRequest {

Expand All @@ -23,15 +21,15 @@ public class SearchRequest {
private SearchRequest(Integer page, Integer size, String order, String query) {
this.page = page != null ? page : 1;
this.size = size != null ? size : 10;
this.order = order;
this.order = order != null ? order : "recent";
this.query = query;
}

public SearchServiceRequest toService() {
return SearchServiceRequest.builder()
.page(page)
.size(size)
.order(order != null ? order : "recent")
.order(order)
.query(query)
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ public enum OrderType {

RECENT("최신순"),
RECOMMEND("좋아요순"),
COMMENT("토크 많은순");
COMMENT("토크 많은순"),
RECENT_COMMENT("최근 등록된 의견순");

private final String text;

Expand All @@ -20,6 +21,7 @@ public static OrderType convertToOrderType(String order) {
case "recent" -> RECENT;
case "recommend" -> RECOMMEND;
case "comment" -> COMMENT;
case "recent-comment" -> RECENT_COMMENT;
default -> RECENT;
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.jisungin.domain.talkroom.repository;

import static com.jisungin.domain.book.QBook.book;
import static com.jisungin.domain.comment.QComment.comment;
import static com.jisungin.domain.talkroom.QTalkRoom.talkRoom;
import static com.jisungin.domain.talkroom.repository.OrderType.RECENT;
import static com.jisungin.domain.talkroom.repository.OrderType.RECENT_COMMENT;
import static com.jisungin.domain.talkroom.repository.OrderType.RECOMMEND;
import static com.jisungin.domain.talkroomlike.QTalkRoomLike.talkRoomLike;
import static com.jisungin.domain.user.QUser.user;
Expand All @@ -11,6 +13,7 @@
import com.jisungin.application.talkroom.response.TalkRoomQueryResponse;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.List;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -77,7 +80,7 @@ public TalkRoomQueryResponse findOneTalkRoom(Long talkRoomId) {

// 토크룸 페이징 조회 쿼리
private List<TalkRoomQueryResponse> findTalkRoomBySearch(long offset, int size, String order, String query) {
return queryFactory.select(new QTalkRoomQueryResponse(
JPAQuery<TalkRoomQueryResponse> jpaQuery = queryFactory.select(new QTalkRoomQueryResponse(
talkRoom.id.as("talkRoomId"),
user.profileImage,
user.name.as("userName"),
Expand All @@ -92,12 +95,25 @@ private List<TalkRoomQueryResponse> findTalkRoomBySearch(long offset, int size,
.join(talkRoom.user, user)
.join(talkRoom.book, book)
.leftJoin(talkRoomLike).on(talkRoom.eq(talkRoomLike.talkRoom))
.groupBy(talkRoom.id)
.from(talkRoom);

addJoinByOrder(jpaQuery, OrderType.convertToOrderType(order));

List<TalkRoomQueryResponse> response = jpaQuery.groupBy(talkRoom.id)
.where(searchQuery(query))
.offset(offset)
.limit(size)
.orderBy(condition(OrderType.convertToOrderType(order)))
.fetch();

return response;
}

private void addJoinByOrder(JPAQuery<?> jpaQuery, OrderType orderType) {
if (RECENT_COMMENT.equals(orderType)) {
jpaQuery
.leftJoin(comment).on(talkRoom.eq(comment.talkRoom));
}
}

private BooleanExpression searchQuery(String search) {
Expand Down Expand Up @@ -130,6 +146,8 @@ private OrderSpecifier<?> condition(OrderType orderType) {
return talkRoom.createDateTime.desc();
} else if (RECOMMEND.equals(orderType)) {
return talkRoomLike.count().desc();
} else if (RECENT_COMMENT.equals(orderType)) {
return comment.createDateTime.max().desc();
}
return OrderByNull.DEFAULT;
}
Comment on lines 146 to 153
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

orderTypeRECENT_COMMENT일 때 max로 정렬 조건을 지정한 이유가 있을까요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

max를 사용하지 않고 gropBy를 TalkRoom.id 로 하니 에러가 발생하더라구요. 그래서 gropBy를 없애고 comment.createDateTime.max().desc() 해결이 되어서 일단은 이렇게 작성해놨습니다!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 알겠습니다!

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -914,6 +915,23 @@ void createTalkRoomWithImage() throws Exception {

}

@Test
@DisplayName("최근 의견이 달린 토론방을 조회 할때 의견이 없다면 빈 값을 보낸다.")
void fetchRecentCommentedDiscussionsWithCommentEmpty() throws Exception {
// given
SearchServiceRequest request = SearchServiceRequest.builder()
.size(3)
.page(1)
.order("recent_comment")
.build();

// when
TalkRoomPageResponse response = talkRoomService.findAllTalkRoom(request, null);

// then
Assertions.assertThat(response.getResponse().getQueryResponse()).isEmpty();
}

private static List<User> listUsers() {
return IntStream.range(0, 10)
.mapToObj(i -> User.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ void getComments() throws Exception {
)
.andDo(print())
.andExpect(status().isOk())
.andDo(document("comment/create",
.andDo(document("comment/find",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
pathParameters(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ void findAllTalkRooms() throws Exception {
parameterWithName("size")
.description("페이지 사이즈"),
parameterWithName("order")
.description("정렬 기준(기본값 최신순) -> RECENT(최신순), RECOMMEND(좋아요순)"),
.description(
"정렬 기준 : recent(최신순), recommend(좋아요순), recent-comment(최근 등록된 의견순)"),
parameterWithName("search")
.description("검색").optional()
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,110 @@ public void getTalkRoomsRelatedBookTotalSize() {
assertThat(anotherTotalCount).isEqualTo(10L);
}

@Test
@DisplayName("최근 의견이 달린 토론방을 가져온다.")
void fetchRecentCommentedDiscussions() throws Exception {
// given
User user = createUser();
userRepository.save(user);

Book book = createBook();
bookRepository.save(book);

List<TalkRoom> talkRooms = IntStream.range(1, 11)
.mapToObj(i -> TalkRoom.builder()
.user(user)
.book(book)
.title("토론방" + i)
.content("내용" + i)
.build())
.toList();
talkRoomRepository.saveAll(talkRooms);

List<Comment> comments = IntStream.range(3, 6)
.mapToObj(i -> Comment.builder()
.user(user)
.talkRoom(talkRooms.get(i))
.content("의견")
.build())
.toList();
commentRepository.saveAll(comments);

SearchServiceRequest request = SearchServiceRequest.builder()
.size(3)
.page(1)
.order("recent-comment")
.build();

// when
List<TalkRoomQueryResponse> response = talkRoomRepository.findAllTalkRoom(request.getOffset(),
request.getSize(), request.getOrder(), request.getQuery());

// then
assertThat("토론방6").isEqualTo(response.get(0).getTitle());
assertThat("토론방5").isEqualTo(response.get(1).getTitle());
assertThat("토론방4").isEqualTo(response.get(2).getTitle());
}

@Test
@DisplayName("최근 의견이 달린 토론방을 가져온다.")
void fetchRecentCommentedDiscussions2() throws Exception {
// given
User user = createUser();
userRepository.save(user);

Book book = createBook();
bookRepository.save(book);

List<TalkRoom> talkRooms = IntStream.range(1, 11)
.mapToObj(i -> TalkRoom.builder()
.user(user)
.book(book)
.title("토론방" + i)
.content("내용" + i)
.build())
.toList();
talkRoomRepository.saveAll(talkRooms);

Comment comment1 = Comment.builder()
.content("의견")
.user(user)
.talkRoom(talkRooms.get(3))
.build();
Comment comment2 = Comment.builder()
.content("의견")
.user(user)
.talkRoom(talkRooms.get(4))
.build();
Comment comment3 = Comment.builder()
.content("의견")
.user(user)
.talkRoom(talkRooms.get(5))
.build();
Comment comment4 = Comment.builder()
.content("의견 추가")
.user(user)
.talkRoom(talkRooms.get(5))
.build();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment 생성 메서드가 있는데 builder를 사용해서 객체를 생성하신 이유가 있나요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

생성 메서드는 TalkRoom 0번 객체에만 만들어지기 때문에 여러 TalkRoom방에 Comment를 생성하기 위해 이렇게 작성했습니다.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment comment1 = createComment(talkRooms.get(3), user);
Comment comment2 = createComment(talkRooms.get(4), user);
Comment comment3 = createComment(talkRooms.get(5), user);
Comment comment4 = createcomment(talkRooms.get(5), user);

commentRepository.saveAll(List.of(comment1, comment2, comment3, comment4));

위와 같이 작성하면 되지 않을까요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네 수정 해서 다시 올렸습니다!


commentRepository.saveAll(List.of(comment1, comment2, comment3, comment4));

SearchServiceRequest request = SearchServiceRequest.builder()
.size(3)
.page(1)
.order("recent-comment")
.build();

// when
List<TalkRoomQueryResponse> response = talkRoomRepository.findAllTalkRoom(request.getOffset(),
request.getSize(), request.getOrder(), request.getQuery());

// then
assertThat("토론방6").isEqualTo(response.get(0).getTitle());
assertThat("토론방5").isEqualTo(response.get(1).getTitle());
assertThat("토론방4").isEqualTo(response.get(2).getTitle());
}

private static Comment createComment(TalkRoom talkRoom, User user) {
return Comment.builder()
.talkRoom(talkRoom)
Expand Down
Loading