Skip to content

Commit

Permalink
[feat] 채팅 메시지 목록 조회 응답 변경 및 빈 채팅창 조회시 에러 해결 (#154)
Browse files Browse the repository at this point in the history
* #153 fix: 채팅창 목록 조회 문제 해결

- 채팅창만이 존재하고 채팅 로그가 없는 경우가 원인이었습니다.

* #153 fix: nextMessageId가 응답되도록 수정

* #153 fix: 필드멤버 명 변경

* #153 fix: 오타 수정
  • Loading branch information
yonghwankim-dev authored Oct 5, 2023
1 parent fc8d4e5 commit 884b891
Show file tree
Hide file tree
Showing 11 changed files with 41 additions and 47 deletions.
3 changes: 2 additions & 1 deletion backend/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ plugins {
id 'com.ewerk.gradle.plugins.querydsl' version '1.0.10'
}

project.base.archivesBaseName('second_hand')
version = '0.1.0-SNAPSHOT'
group = 'codesquard'
version = '0.0.1-SNAPSHOT'

java {
sourceCompatibility = '11'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,20 @@ public ApiResponse<ChatLogSendResponse> sendMessage(
@GetMapping("/chats/{chatRoomId}")
public DeferredResult<ApiResponse<ChatLogListResponse>> readMessages(
@PathVariable Long chatRoomId,
@RequestParam(required = false, defaultValue = "0") Long messageIndex,
@RequestParam(required = false, defaultValue = "0") Long messageId,
@PageableDefault Pageable pageable,
@AuthPrincipal Principal principal) {
log.info("메시지 읽기 요청 : chatRoomId={}, cursor={}, pageable={}, 요청한 아이디={}", chatRoomId, messageIndex, pageable,
log.info("메시지 읽기 요청 : chatRoomId={}, cursor={}, pageable={}, 요청한 아이디={}", chatRoomId, messageId, pageable,
principal.getLoginId());

DeferredResult<ApiResponse<ChatLogListResponse>> deferredResult = new DeferredResult<>(10000L);
chatService.putMessageIndex(deferredResult, messageIndex);
chatService.putMessageIndex(deferredResult, messageId);

deferredResult.onCompletion(() -> chatService.removeMessageIndex(deferredResult));
deferredResult.onTimeout(() -> deferredResult.setErrorResult(
ApiResponse.of(HttpStatus.REQUEST_TIMEOUT, "새로운 채팅 메시지가 존재하지 않습니다.", Collections.emptyList())));

ChatLogListResponse response = chatLogService.readMessages(chatRoomId, principal, messageIndex, pageable);
ChatLogListResponse response = chatLogService.readMessages(chatRoomId, principal, messageId, pageable);

if (!response.isEmptyChat()) {
deferredResult.setResult(ApiResponse.ok("채팅 메시지 목록 조회가 완료되었습니다.", response));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,13 @@ public ChatLogListResponse readMessages(Long chatRoomId, Principal principal, Lo
boolean hasNext = slice.hasNext();
Long nextCursor = getNextCursor(messageResponses, hasNext);

return new ChatLogListResponse(chatPartnerName, ChatLogItemResponse.from(item), messageResponses, hasNext,
nextCursor);
return new ChatLogListResponse(chatPartnerName, ChatLogItemResponse.from(item), messageResponses, nextCursor);
}

private Long getNextCursor(List<ChatLogMessageResponse> contents, boolean hasNext) {
Long nextCursor = null;
if (hasNext) {
nextCursor = contents.get(contents.size() - 1).getMessageIndex();
nextCursor = contents.get(contents.size() - 1).getMessageId();
}
return nextCursor;
}
Expand Down
27 changes: 20 additions & 7 deletions backend/src/main/java/codesquard/app/api/chat/ChatRoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

Expand All @@ -19,6 +20,7 @@
import codesquard.app.api.chat.response.ChatRoomListResponse;
import codesquard.app.api.errors.errorcode.ErrorCode;
import codesquard.app.api.errors.exception.NotFoundResourceException;
import codesquard.app.domain.chat.ChatLog;
import codesquard.app.domain.chat.ChatLogCountRepository;
import codesquard.app.domain.chat.ChatLogRepository;
import codesquard.app.domain.chat.ChatRoom;
Expand Down Expand Up @@ -79,6 +81,8 @@ public ChatRoomListResponse readAllChatRoom(Principal principal, Pageable pageab
List<Long> itemIds = itemRepository.findAllByMemberId(principal.getMemberId()).stream()
.map(Item::getId)
.collect(Collectors.toUnmodifiableList());
log.info("회원이 판매하는 상품 아이디 : {}", itemIds);

// 1. 내가 팔고 있는 상품들의 등록번호 조회 조건
BooleanExpression chatRoomOfSellingItemsCondition = QChatRoom.chatRoom.item.id.in(itemIds);
// 2. 내가 사려고 하는 상품에 대한 채팅방 목록 조회 조건
Expand All @@ -87,9 +91,11 @@ public ChatRoomListResponse readAllChatRoom(Principal principal, Pageable pageab
whereBuilder.andAnyOf(chatRoomOfSellingItemsCondition, chatRoomOfBuyingItemsCondition);

Slice<ChatRoom> slice = chatRoomPaginationRepository.searchBySlice(whereBuilder, pageable);
log.info("채팅방 페이징 조회 결과 개수 : {}", slice.getSize());

List<ChatRoomItemResponse> contents = slice.getContent().stream()
.map(getChatRoomItemResponseMapper(newMessageMap, principal))
.filter(Objects::nonNull)
.sorted(Comparator.comparing(ChatRoomItemResponse::getLastSendTime).reversed())
.collect(Collectors.toUnmodifiableList());
boolean hasNext = slice.hasNext();
Expand All @@ -101,13 +107,19 @@ public ChatRoomListResponse readAllChatRoom(Principal principal, Pageable pageab
private Function<ChatRoom, ChatRoomItemResponse> getChatRoomItemResponseMapper(Map<Long, Long> newMessageMap,
Principal principal) {

return chatRoom -> ChatRoomItemResponse.of(
chatRoom,
chatRoom.getItem(),
getChatRoomPartner(principal, chatRoom),
chatLogRepository.findFirstByChatRoomIdOrderByCreatedAtDesc(chatRoom.getId())
.orElseThrow(() -> new NotFoundResourceException(ErrorCode.NOT_FOUND_CHAT_LOG)),
newMessageMap.getOrDefault(chatRoom.getId(), 0L));
return chatRoom -> {
ChatLog chatLog = chatLogRepository.findFirstByChatRoomIdOrderByCreatedAtDesc(chatRoom.getId())
.orElse(null);
if (chatLog == null) {
return null;
}
return ChatRoomItemResponse.of(
chatRoom,
chatRoom.getItem(),
getChatRoomPartner(principal, chatRoom),
chatLog,
newMessageMap.getOrDefault(chatRoom.getId(), 0L));
};
}

private Member getChatRoomPartner(Principal principal, ChatRoom chatRoom) {
Expand Down Expand Up @@ -138,6 +150,7 @@ public ChatRoomListResponse readAllChatRoomByItem(Long itemId, Principal princip

List<ChatRoomItemResponse> contents = slice.getContent().stream()
.map(getChatRoomItemResponseMapper(newMessageMap, principal))
.filter(Objects::nonNull)
.sorted(Comparator.comparing(ChatRoomItemResponse::getLastSendTime).reversed())
.collect(Collectors.toUnmodifiableList());
boolean hasNext = slice.hasNext();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package codesquard.app.api.chat.response;

import static codesquard.app.api.item.response.ItemResponses.*;

import java.util.Collections;
import java.util.List;

Expand All @@ -15,22 +13,14 @@
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class ChatLogListResponse {

private String chatPartnerName;
private ChatLogItemResponse item;
private List<ChatLogMessageResponse> chat;
private Paging paging;

public ChatLogListResponse(String chatPartnerName, ChatLogItemResponse item, List<ChatLogMessageResponse> chat,
boolean hasNext, Long nextCursor) {
this.chatPartnerName = chatPartnerName;
this.item = item;
this.chat = chat;
this.paging = Paging.create(nextCursor, hasNext);
}
private Long nextMessageId;

public static ChatLogListResponse emptyResponse(String chatPartnerName, Item item) {
return new ChatLogListResponse(chatPartnerName, ChatLogItemResponse.from(item), Collections.emptyList(), false,
null);
return new ChatLogListResponse(chatPartnerName, ChatLogItemResponse.from(item), Collections.emptyList(), null);
}

public boolean isEmptyChat() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ChatLogMessageResponse {
private Long messageIndex;
private Long messageId;
private Boolean isMe;
private String message;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package codesquard.app.api.chat.response;

import com.fasterxml.jackson.annotation.JsonProperty;

import codesquard.app.domain.chat.ChatRoom;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
Expand All @@ -12,9 +10,8 @@
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ChatRoomCreateResponse {

@JsonProperty(value = "chatRoomId")
private Long id;

private Long chatRoomId;

public static ChatRoomCreateResponse from(ChatRoom chatRoom) {
return new ChatRoomCreateResponse(chatRoom.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class ChatLogPaginationRepository {
public Slice<ChatLog> searchBySlice(BooleanBuilder whereBuilder, Pageable pageable) {
List<ChatLog> chatLogs = queryFactory.selectFrom(chatLog)
.where(whereBuilder)
.orderBy(chatLog.id.asc())
.orderBy(chatLog.id.asc(), chatLog.createdAt.asc())
.limit(pageable.getPageSize() + 1)
.fetch();
return checkLastPage(pageable, chatLogs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public void readMessages() throws Exception {
ChatLog chatLog = new ChatLog("안녕하세요. 롤러블레이브를 사고 싶습니다. 만원만 깍아주세요.", "23Yong", "carlynne", chatRoom, 1);
ChatLogMessageResponse messageResponse = ChatLogMessageResponse.from(chatLog, Principal.from(buyer));
ChatLogListResponse response = new ChatLogListResponse("carlynne", itemResponse, List.of(messageResponse),
false, null);
null);
given(chatLogService.readMessages(anyLong(), any(Principal.class), anyLong(), any(Pageable.class)))
.willReturn(response);
int chatRoomId = 1;
Expand Down Expand Up @@ -168,7 +168,7 @@ public void readMessages() throws Exception {
public void readMessagesWithTimeout() throws Exception {
// given
ChatLogItemResponse itemResponse = null;
ChatLogListResponse response = new ChatLogListResponse("carlynne", itemResponse, List.of(), false, null);
ChatLogListResponse response = new ChatLogListResponse("carlynne", itemResponse, List.of(), null);
given(chatLogService.readMessages(
anyLong(),
any(Principal.class),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import static org.mockito.BDDMockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import java.util.HashMap;
Expand All @@ -27,7 +26,6 @@
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import codesquard.app.ControllerTestSupport;
Expand Down Expand Up @@ -78,7 +76,7 @@ public void setup() {
public void createChatRoom() throws Exception {
// given
Map<String, Object> responseBody = new HashMap<>();
responseBody.put("id", 1L);
responseBody.put("chatRoomId", 1L);

ChatRoomCreateResponse response = objectMapper.readValue(objectMapper.writeValueAsString(responseBody),
ChatRoomCreateResponse.class);
Expand All @@ -93,7 +91,7 @@ public void createChatRoom() throws Exception {
.andExpect(status().isCreated())
.andExpect(jsonPath("statusCode").value(equalTo(201)))
.andExpect(jsonPath("message").value(equalTo("채팅방 생성을 완료하였습니다.")))
.andExpect(jsonPath("data.id").value(equalTo(1)));
.andExpect(jsonPath("data.chatRoomId").value(equalTo(1)));
}

@DisplayName("회원은 채팅방 목록을 요청한다")
Expand All @@ -120,11 +118,7 @@ public void readAllChatRoom() throws Exception {
.willReturn(response);

// when & then
MvcResult asyncListener = mockMvc.perform(get("/api/chats"))
.andExpect(request().asyncStarted())
.andReturn();

mockMvc.perform(asyncDispatch(asyncListener))
mockMvc.perform(get("/api/chats"))
.andExpect(status().isOk())
.andExpect(jsonPath("statusCode").value(equalTo(200)))
.andExpect(jsonPath("message").value(equalTo("채팅방 목록 조회를 완료하였습니다.")))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public void createChatRoom() {
// then
assertAll(() -> {
assertThat(response)
.extracting("id")
.extracting("chatRoomId")
.isNotNull();
});
}
Expand Down

0 comments on commit 884b891

Please sign in to comment.