From 0891f324eeefffd331248d2e63a940e4cc617a38 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Sun, 13 Oct 2024 22:28:04 +0900 Subject: [PATCH 01/34] =?UTF-8?q?Refactor=20#258=20:=20=EC=82=AC=EC=9A=A9?= =?UTF-8?q?=ED=95=98=EC=A7=80=20=EC=95=8A=EB=8A=94=20=ED=81=B4=EB=9E=98?= =?UTF-8?q?=EC=8A=A4=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ChatMessageMongoCustomRepository.java | 14 ---- .../ChatMessageMongoCustomRepositoryImpl.java | 78 ------------------- 2 files changed, 92 deletions(-) delete mode 100644 src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java delete mode 100644 src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepositoryImpl.java diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java deleted file mode 100644 index 18e5278b..00000000 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.prgms.locomocoserver.chat.domain.mongo; - -import java.util.List; -import java.util.Optional; - -public interface ChatMessageMongoCustomRepository { - Optional findLatestMessageByRoomId(Long roomId); - - List findAllChatMessagesByRoomId(Long roomId, String cursorValue, int pageSize); - - int unReadMessageCount(Long roomId, String lastReadMsgId); - - void deleteAllChatMessages(Long roomId); -} diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepositoryImpl.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepositoryImpl.java deleted file mode 100644 index 8caad5db..00000000 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepositoryImpl.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.prgms.locomocoserver.chat.domain.mongo; - -import lombok.RequiredArgsConstructor; -import org.bson.types.ObjectId; -import org.prgms.locomocoserver.chat.exception.ChatErrorType; -import org.prgms.locomocoserver.chat.exception.ChatException; -import org.springframework.data.domain.Sort; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.core.query.Criteria; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; -import java.util.Optional; - -@Repository -@RequiredArgsConstructor -public class ChatMessageMongoCustomRepositoryImpl implements ChatMessageMongoCustomRepository { - - private static final String BASE_CHATROOM_NAME = "chat_messages_"; - private final MongoTemplate mongoTemplate; - - @Override - @Transactional(readOnly = true) - public Optional findLatestMessageByRoomId(Long roomId) { - String collectionName = getChatRoomName(roomId); - Query query = new Query().with(Sort.by(Sort.Direction.DESC, "_id")).limit(1); - - ChatMessageMongo lastMessage = mongoTemplate.findOne(query, ChatMessageMongo.class, collectionName); - return Optional.of(lastMessage); - } - - @Override - @Transactional(readOnly = true) - public List findAllChatMessagesByRoomId(Long roomId, String cursorValue, int pageSize) { - String collectionName = getChatRoomName(roomId); - Query query = new Query(); - - if (cursorValue != null && !cursorValue.trim().isEmpty() && !"null".equals(cursorValue)) { - ObjectId cursorObjectId = new ObjectId(cursorValue); - query.addCriteria(Criteria.where("_id").lt(cursorObjectId)); - } - query.with(Sort.by(Sort.Direction.DESC, "_id")).limit(pageSize); - - try { - return mongoTemplate.find(query, ChatMessageMongo.class, collectionName); - } catch (Exception e) { - throw new ChatException(ChatErrorType.CHAT_MESSAGE_NOT_FOUND, "채팅방에 메시지가 없습니다."); - } - } - - @Override - @Transactional(readOnly = true) - public int unReadMessageCount(Long roomId, String lastReadMsgId) { - ObjectId lastReadMsgObjectId = new ObjectId(lastReadMsgId); - - Query query = new Query() - .addCriteria(Criteria.where("_id").gt(lastReadMsgObjectId)); - - return (int) mongoTemplate.count(query, ChatMessageMongo.class, getChatRoomName(roomId)); - } - - @Override - @Transactional - public void deleteAllChatMessages(Long roomId) { - String collectionName = getChatRoomName(roomId); - try { - mongoTemplate.dropCollection(collectionName); - } catch (Exception e) { - throw new RuntimeException("채팅방 삭제를 실패했습니다"); - } - } - - private String getChatRoomName(Long roomId) { - return BASE_CHATROOM_NAME + roomId; - } -} From 4ce8dc6f87c9bff909b8b2fe5c808f2ec32715f6 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Mon, 14 Oct 2024 00:00:07 +0900 Subject: [PATCH 02/34] =?UTF-8?q?refactor=20#258=20:=20=EA=B8=B0=EC=A1=B4?= =?UTF-8?q?=20document=20=ED=98=95=ED=83=9C=EB=B3=80=EA=B2=BD=20=EB=B0=8F?= =?UTF-8?q?=20=EB=A0=88=ED=8F=AC=EC=A7=80=ED=86=A0=EB=A6=AC=20=EB=A9=94?= =?UTF-8?q?=EC=84=9C=EB=93=9C=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/domain/mongo/ChatMessageMongo.java | 15 ++++++++-- .../ChatMessageMongoCustomRepository.java | 28 +++++++++++++++++++ .../mongo/ChatMessageMongoRepository.java | 16 +++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java create mode 100644 src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoRepository.java diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongo.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongo.java index b5eceac6..a618ec0c 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongo.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongo.java @@ -3,6 +3,7 @@ import jakarta.persistence.Id; import lombok.Builder; import lombok.Getter; +import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import java.time.LocalDateTime; @@ -10,23 +11,33 @@ import java.util.List; @Getter -@Document +@Document(collection = "chat_messages") public class ChatMessageMongo { @Id private String id; + @Indexed + private String chatRoomId; private String senderId; private String message; private List imageUrls; private boolean isNotice; + @Indexed private LocalDateTime createdAt; @Builder - public ChatMessageMongo(String senderId, String message, List imageUrls, boolean isNotice, LocalDateTime createdAt) { + public ChatMessageMongo(String chatRoomId, String senderId, String message, List imageUrls, boolean isNotice, LocalDateTime createdAt) { + this.chatRoomId = chatRoomId; this.senderId = senderId; this.message = message; this.imageUrls = imageUrls; this.isNotice = isNotice; this.createdAt = createdAt; } + + public void validate() { + if (message == null || message.trim().isEmpty()) { + throw new IllegalArgumentException("Message cannot be null or empty"); + } + } } diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java new file mode 100644 index 00000000..6fcd5a41 --- /dev/null +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java @@ -0,0 +1,28 @@ +package org.prgms.locomocoserver.chat.domain.mongo; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +@Repository +@RequiredArgsConstructor +public class ChatMessageMongoCustomRepository { + + private final MongoTemplate mongoTemplate; + + @Transactional(readOnly = true) + public List findAllChatMessages(Long roomId, String cursorValue, int pageSize) { + Query query = new Query(); + query.addCriteria(Criteria.where("chatRoomId").is(roomId.toString()) + .and("createdAt").lt(LocalDateTime.parse(cursorValue))); + query.limit(pageSize); + + return mongoTemplate.find(query, ChatMessageMongo.class); + } +} diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoRepository.java new file mode 100644 index 00000000..10af5474 --- /dev/null +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoRepository.java @@ -0,0 +1,16 @@ +package org.prgms.locomocoserver.chat.domain.mongo; + +import org.springframework.data.mongodb.repository.MongoRepository; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +public interface ChatMessageMongoRepository extends MongoRepository { + + Optional findTopByChatRoomIdOrderByCreatedAtDesc(String chatRoomId); + + long countByChatRoomIdAndIdGreaterThan(String chatRoomId, String lastReadMsgId); + + void deleteByChatRoomId(String chatRoomId); +} From 8274547bdd824331126be5dfa6bbbc3106221478 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Mon, 14 Oct 2024 13:21:50 +0900 Subject: [PATCH 03/34] =?UTF-8?q?refactor=20#258=20:=20=EA=B8=B0=EC=A1=B4?= =?UTF-8?q?=20collection=20=EC=83=9D=EC=84=B1=20=EA=B4=80=EB=A0=A8=20?= =?UTF-8?q?=EB=A9=94=EC=84=9C=EB=93=9C=20=EC=88=98=EC=A0=95=20=EB=B0=8F=20?= =?UTF-8?q?=EC=83=88=20=EB=A0=88=ED=8F=AC=EC=A7=80=ED=86=A0=EB=A6=AC=20?= =?UTF-8?q?=EB=A9=94=EC=84=9C=EB=93=9C=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatActivityService.java | 6 ++-- .../chat/application/ChatRoomService.java | 1 - .../application/MongoChatMessageService.java | 28 ++++++------------- 3 files changed, 11 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java index 66935718..e1d04e5e 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java @@ -2,7 +2,7 @@ import lombok.RequiredArgsConstructor; import org.prgms.locomocoserver.chat.domain.ChatParticipant; -import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoCustomRepository; +import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoRepository; import org.prgms.locomocoserver.chat.domain.querydsl.ChatParticipantCustomRepository; import org.prgms.locomocoserver.chat.dto.request.ChatActivityRequestDto; import org.prgms.locomocoserver.chat.exception.ChatErrorType; @@ -15,7 +15,7 @@ public class ChatActivityService { private final ChatParticipantCustomRepository chatParticipantRepository; - private final ChatMessageMongoCustomRepository chatMessageMongoCustomRepository; + private final ChatMessageMongoRepository chatMessageMongoRepository; @Transactional public void updateLastReadMessage(Long chatRoomId, ChatActivityRequestDto requestDto) { @@ -29,6 +29,6 @@ public int unReadMessageCount(Long roomId, String lastReadMsgId) { if (lastReadMsgId == null) { return 0; } - return chatMessageMongoCustomRepository.unReadMessageCount(roomId, lastReadMsgId); + return (int) chatMessageMongoRepository.countByChatRoomIdAndIdGreaterThan(roomId.toString(), lastReadMsgId); } } diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java index 30d0b5a1..eb65e9c7 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java @@ -59,7 +59,6 @@ public ChatRoom createChatRoom(ChatCreateRequestDto requestDto) { chatRoom.addChatParticipant(chatParticipant); chatRoomRepository.save(chatRoom); // mysql chat room create - mongoChatMessageService.createChatRoom(chatRoom.getId()); // mongo chat room create chatMessagePolicy.saveEnterMessage(chatRoom.getId(), chatParticipant.getUser()); diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/MongoChatMessageService.java b/src/main/java/org/prgms/locomocoserver/chat/application/MongoChatMessageService.java index cf2558ed..910b0caa 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/MongoChatMessageService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/MongoChatMessageService.java @@ -5,12 +5,13 @@ import org.prgms.locomocoserver.chat.domain.ChatRoomRepository; import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongo; import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoCustomRepository; +import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoRepository; +import org.prgms.locomocoserver.chat.domain.querydsl.ChatRoomCustomRepository; import org.prgms.locomocoserver.chat.dto.ChatMessageDto; import org.prgms.locomocoserver.chat.dto.ChatUserInfo; import org.prgms.locomocoserver.chat.dto.request.ChatMessageRequestDto; import org.prgms.locomocoserver.chat.exception.ChatErrorType; import org.prgms.locomocoserver.chat.exception.ChatException; -import org.prgms.locomocoserver.chat.domain.querydsl.ChatRoomCustomRepository; import org.prgms.locomocoserver.user.application.UserService; import org.prgms.locomocoserver.user.domain.User; import org.prgms.locomocoserver.user.exception.UserException; @@ -23,7 +24,6 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.stream.Collectors; @Primary @@ -33,26 +33,15 @@ public class MongoChatMessageService implements ChatMessagePolicy { private static final String BASE_CHATROOM_NAME = "chat_messages_"; private final MongoTemplate mongoTemplate; + private final ChatMessageMongoRepository chatMessageMongoRepository; private final ChatMessageMongoCustomRepository chatMessageMongoCustomRepository; private final UserService userService; private final ChatRoomRepository chatRoomRepository; private final ChatRoomCustomRepository chatRoomCustomRepository; - @Transactional - public ChatRoom createChatRoom(Long roomId) { - String collectionName = BASE_CHATROOM_NAME + roomId; - - if (!mongoTemplate.collectionExists(collectionName)) { - mongoTemplate.createCollection(collectionName); - } - - return chatRoomRepository.findById(roomId).orElseThrow(() -> new ChatException(ChatErrorType.CHATROOM_NOT_FOUND)); - } - @Transactional public ChatMessageDto saveEnterMessage(Long roomId, User sender) { - String collectionName = BASE_CHATROOM_NAME + roomId; - ChatMessageMongo chatMessageMongo = mongoTemplate.save(toEnterMessage(sender), collectionName); + ChatMessageMongo chatMessageMongo = chatMessageMongoRepository.save(toEnterMessage(sender)); return ChatMessageDto.of(roomId, chatMessageMongo, ChatUserInfo.of(sender)); } @@ -74,13 +63,12 @@ public ChatMessageDto saveChatMessage(Long roomId, ChatMessageRequestDto message @Override @Transactional public ChatMessageDto saveChatMessageWithImage(Long roomId, List imageUrls, ChatMessageRequestDto request) { - String collectionName = BASE_CHATROOM_NAME + roomId; User participant = userService.getById(request.senderId()); ChatRoom chatRoom = chatRoomRepository.findByIdAndDeletedAtIsNull(roomId) .orElseThrow(() -> new ChatException(ChatErrorType.CHATROOM_NOT_FOUND)); - ChatMessageMongo chatMessageMongo = mongoTemplate.save(request.toChatMessageMongo(false, imageUrls), collectionName); + ChatMessageMongo chatMessageMongo = mongoTemplate.save(request.toChatMessageMongo(false, imageUrls)); chatRoom.updateUpdatedAt(); return ChatMessageDto.of(roomId, imageUrls, chatMessageMongo, ChatUserInfo.of(participant)); @@ -88,7 +76,7 @@ public ChatMessageDto saveChatMessageWithImage(Long roomId, List imageUr @Transactional(readOnly = true) public List getAllChatMessages(Long roomId, String cursorValue, int pageSize) { - List chatMessages = chatMessageMongoCustomRepository.findAllChatMessagesByRoomId(roomId, cursorValue, pageSize); + List chatMessages = chatMessageMongoCustomRepository.findAllChatMessages(roomId, cursorValue, pageSize); Map userMap = getUserMap(roomId); return createChatMessageDtos(roomId, chatMessages, userMap); @@ -96,12 +84,12 @@ public List getAllChatMessages(Long roomId, String cursorValue, @Transactional public void deleteChatMessages(ChatRoom chatRoom) { - chatMessageMongoCustomRepository.deleteAllChatMessages(chatRoom.getId()); + chatMessageMongoRepository.deleteByChatRoomId(chatRoom.getId().toString()); } @Transactional(readOnly = true) public ChatMessageDto getLastChatMessage(Long roomId) { - ChatMessageMongo lastMessage = chatMessageMongoCustomRepository.findLatestMessageByRoomId(roomId) + ChatMessageMongo lastMessage = chatMessageMongoRepository.findTopByChatRoomIdOrderByCreatedAtDesc(roomId.toString()) .orElseThrow(() -> new ChatException(ChatErrorType.CHAT_MESSAGE_NOT_FOUND)); ChatUserInfo chatUserInfo = getChatUserInfo(lastMessage.getSenderId()); From f5f35af53ea9519cf32ddb7957400427ec079f21 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Mon, 14 Oct 2024 19:42:12 +0900 Subject: [PATCH 04/34] =?UTF-8?q?refactor=20#258=20:=20collection=20?= =?UTF-8?q?=EC=9D=B4=EB=A6=84=20=EC=82=AC=EC=9A=A9=ED=95=98=EB=8A=94=20?= =?UTF-8?q?=EB=A9=94=EC=84=9C=EB=93=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../application/MongoChatMessageService.java | 19 +++++-------------- .../dto/request/ChatMessageRequestDto.java | 3 ++- 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/MongoChatMessageService.java b/src/main/java/org/prgms/locomocoserver/chat/application/MongoChatMessageService.java index 910b0caa..e186417d 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/MongoChatMessageService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/MongoChatMessageService.java @@ -16,7 +16,6 @@ import org.prgms.locomocoserver.user.domain.User; import org.prgms.locomocoserver.user.exception.UserException; import org.springframework.context.annotation.Primary; -import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -31,8 +30,6 @@ @RequiredArgsConstructor public class MongoChatMessageService implements ChatMessagePolicy { - private static final String BASE_CHATROOM_NAME = "chat_messages_"; - private final MongoTemplate mongoTemplate; private final ChatMessageMongoRepository chatMessageMongoRepository; private final ChatMessageMongoCustomRepository chatMessageMongoCustomRepository; private final UserService userService; @@ -41,26 +38,24 @@ public class MongoChatMessageService implements ChatMessagePolicy { @Transactional public ChatMessageDto saveEnterMessage(Long roomId, User sender) { - ChatMessageMongo chatMessageMongo = chatMessageMongoRepository.save(toEnterMessage(sender)); + ChatMessageMongo chatMessageMongo = chatMessageMongoRepository.save(toEnterMessage(roomId, sender)); return ChatMessageDto.of(roomId, chatMessageMongo, ChatUserInfo.of(sender)); } @Transactional public ChatMessageDto saveChatMessage(Long roomId, ChatMessageRequestDto message) { - String collectionName = BASE_CHATROOM_NAME + roomId; User participant = userService.getById(message.senderId()); ChatRoom chatRoom = chatRoomRepository.findByIdAndDeletedAtIsNull(roomId) .orElseThrow(() -> new ChatException(ChatErrorType.CHATROOM_NOT_FOUND)); - ChatMessageMongo chatMessageMongo = mongoTemplate.save(message.toChatMessageMongo(false, null), collectionName); + ChatMessageMongo chatMessageMongo = chatMessageMongoRepository.save(message.toChatMessageMongo(roomId, false, null)); chatRoom.updateUpdatedAt(); return ChatMessageDto.of(roomId, chatMessageMongo, ChatUserInfo.of(participant)); } - @Override @Transactional public ChatMessageDto saveChatMessageWithImage(Long roomId, List imageUrls, ChatMessageRequestDto request) { User participant = userService.getById(request.senderId()); @@ -68,7 +63,7 @@ public ChatMessageDto saveChatMessageWithImage(Long roomId, List imageUr ChatRoom chatRoom = chatRoomRepository.findByIdAndDeletedAtIsNull(roomId) .orElseThrow(() -> new ChatException(ChatErrorType.CHATROOM_NOT_FOUND)); - ChatMessageMongo chatMessageMongo = mongoTemplate.save(request.toChatMessageMongo(false, imageUrls)); + ChatMessageMongo chatMessageMongo = chatMessageMongoRepository.save(request.toChatMessageMongo(roomId, false, imageUrls)); chatRoom.updateUpdatedAt(); return ChatMessageDto.of(roomId, imageUrls, chatMessageMongo, ChatUserInfo.of(participant)); @@ -96,12 +91,8 @@ public ChatMessageDto getLastChatMessage(Long roomId) { return ChatMessageDto.of(roomId, lastMessage, chatUserInfo); } - public String getChatRoomName(Long roomId) { - return BASE_CHATROOM_NAME + roomId; - } - - private ChatMessageMongo toEnterMessage(User participant) { - return ChatMessageMongo.builder().senderId(participant.getId().toString()).createdAt(LocalDateTime.now()) + private ChatMessageMongo toEnterMessage(Long roomId, User participant) { + return ChatMessageMongo.builder().chatRoomId(roomId.toString()).senderId(participant.getId().toString()).createdAt(LocalDateTime.now()) .message(participant.getNickname() + "님이 입장하셨습니다.").isNotice(true).build(); } diff --git a/src/main/java/org/prgms/locomocoserver/chat/dto/request/ChatMessageRequestDto.java b/src/main/java/org/prgms/locomocoserver/chat/dto/request/ChatMessageRequestDto.java index 0c36ef01..e55007b6 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/dto/request/ChatMessageRequestDto.java +++ b/src/main/java/org/prgms/locomocoserver/chat/dto/request/ChatMessageRequestDto.java @@ -28,8 +28,9 @@ public ChatMessage toChatMessageEntity(User sender, ChatRoom chatRoom, boolean i .isNotice(isNotice).build(); } - public ChatMessageMongo toChatMessageMongo(boolean isNotice, List imageUrls) { + public ChatMessageMongo toChatMessageMongo(Long chatRoomId, boolean isNotice, List imageUrls) { return ChatMessageMongo.builder() + .chatRoomId(chatRoomId.toString()) .senderId(senderId.toString()) .message(message) .imageUrls(imageUrls) From 91fe154f73fc5f6a56b113f7a67c310c881ad92f Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Tue, 15 Oct 2024 20:07:48 +0900 Subject: [PATCH 05/34] =?UTF-8?q?refactor=20#258=20:=20chatRoom=20?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=20=EC=8B=9C=EC=97=90=EB=8A=94=20updatedAt=20?= =?UTF-8?q?=ED=95=84=EB=93=9C=20=EA=B8=B0=EC=A4=80=20=EC=A0=95=EB=A0=AC=20?= =?UTF-8?q?=EB=B0=8F=20=EC=BB=A4=EC=84=9C=EA=B0=92=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../locomocoserver/chat/application/ChatRoomService.java | 6 ++++-- .../chat/domain/querydsl/ChatRoomCustomRepository.java | 2 +- .../chat/domain/querydsl/ChatRoomCustomRepositoryImpl.java | 6 ++++-- .../chat/presentation/ChatRoomController.java | 2 +- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java index eb65e9c7..85d0eb51 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java @@ -19,6 +19,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.time.LocalDateTime; import java.util.List; import java.util.Objects; @@ -81,8 +82,8 @@ public ChatMessageDto saveEnterMessage(ChatEnterRequestDto requestDto) { } @Transactional(readOnly = true) - public List getAllChatRoom(Long userId, Long cursor, int pageSize) { - if (cursor == null) cursor = Long.MAX_VALUE; + public List getAllChatRoom(Long userId, String cursor, int pageSize) { + if (cursor == null) cursor = LocalDateTime.now().toString(); List chatRooms = chatRoomCustomRepository.findByParticipantsId(userId, cursor, pageSize); List chatRoomDtos = chatRooms.stream() @@ -90,6 +91,7 @@ public List getAllChatRoom(Long userId, Long cursor, int pageSize) ChatMessageDto lastMessageDto = chatMessagePolicy.getLastChatMessage(chatRoom.getId()); ChatParticipant chatParticipant = getChatParticipant(chatRoom, userId); + log.info(chatRoom.getChatParticipants().get(0).getLastReadMessageId()); int unReadMsgCnt = chatActivityService.unReadMessageCount(chatRoom.getId(), chatParticipant.getLastReadMessageId()); return ChatRoomDto.of(chatRoom, unReadMsgCnt, lastMessageDto); }) diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/querydsl/ChatRoomCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/querydsl/ChatRoomCustomRepository.java index 7d495cfc..25ebb862 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/querydsl/ChatRoomCustomRepository.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/querydsl/ChatRoomCustomRepository.java @@ -6,6 +6,6 @@ import java.util.List; public interface ChatRoomCustomRepository { - List findByParticipantsId(Long userId, Long cursorId, int pageSize); + List findByParticipantsId(Long userId, String cursor, int pageSize); List findParticipantsByRoomId(Long roomId); } diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/querydsl/ChatRoomCustomRepositoryImpl.java b/src/main/java/org/prgms/locomocoserver/chat/domain/querydsl/ChatRoomCustomRepositoryImpl.java index 8a823757..fb76fb9a 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/querydsl/ChatRoomCustomRepositoryImpl.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/querydsl/ChatRoomCustomRepositoryImpl.java @@ -10,6 +10,7 @@ import org.prgms.locomocoserver.user.domain.User; import org.springframework.stereotype.Repository; +import java.time.LocalDateTime; import java.util.List; @Repository @@ -19,7 +20,7 @@ public class ChatRoomCustomRepositoryImpl implements ChatRoomCustomRepository { private final JPAQueryFactory queryFactory; @Override - public List findByParticipantsId(Long userId, Long cursorId, int pageSize) { + public List findByParticipantsId(Long userId, String cursor, int pageSize) { QChatRoom chatRoom = QChatRoom.chatRoom; QChatParticipant chatParticipant = QChatParticipant.chatParticipant; QUser user = QUser.user; @@ -31,9 +32,10 @@ public List findByParticipantsId(Long userId, Long cursorId, int pageS .join(chatRoom.chatParticipants, chatParticipant) .where( chatParticipant.user.id.eq(userId) - .and(chatRoom.id.lt(cursorId)) + .and(chatRoom.updatedAt.lt(LocalDateTime.parse(cursor))) .and(chatParticipant.deletedAt.isNull()) ) + .orderBy(chatRoom.updatedAt.desc()) .limit(pageSize) .fetch(); diff --git a/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatRoomController.java b/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatRoomController.java index 8fbc39d9..f4285ffe 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatRoomController.java +++ b/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatRoomController.java @@ -24,7 +24,7 @@ public class ChatRoomController { @Operation(summary = "채팅방 목록 조회", description = "userId 기반 채팅방 조회") @GetMapping("/chats/rooms/{userId}") public ResponseEntity> getAllChatRooms(@PathVariable Long userId, - @RequestParam(name = "cursor", required = false) Long cursor, + @RequestParam(name = "cursor", required = false) String cursor, @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) { List chatRoomDtos = chatRoomService.getAllChatRoom(userId, cursor, pageSize); return ResponseEntity.ok(chatRoomDtos); From 93684f297be1919e673ce1e98fa97718a12c8743 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Tue, 15 Oct 2024 20:08:02 +0900 Subject: [PATCH 06/34] =?UTF-8?q?test=20#258=20:=20chatRoom=20=EC=A1=B0?= =?UTF-8?q?=ED=9A=8C=20=EC=8B=9C=EC=97=90=EB=8A=94=20updatedAt=20=ED=95=84?= =?UTF-8?q?=EB=93=9C=20=EA=B8=B0=EC=A4=80=20=EC=A0=95=EB=A0=AC=20=EB=B0=8F?= =?UTF-8?q?=20=EC=BB=A4=EC=84=9C=EA=B0=92=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatRoomServiceTest.java | 71 ++++++++++--------- .../repository/ChatRoomRepositoryTest.java | 4 +- .../user/application/UserServiceTest.java | 2 +- 3 files changed, 42 insertions(+), 35 deletions(-) diff --git a/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java b/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java index a06f6fa3..f0b97496 100644 --- a/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java +++ b/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java @@ -1,19 +1,9 @@ package org.prgms.locomocoserver.chat.application; -import static org.assertj.core.api.Assertions.assertThat; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.prgms.locomocoserver.chat.domain.ChatMessageRepository; -import org.prgms.locomocoserver.chat.domain.ChatParticipantRepository; -import org.prgms.locomocoserver.chat.domain.ChatRoom; -import org.prgms.locomocoserver.chat.domain.ChatRoomRepository; +import org.prgms.locomocoserver.chat.domain.*; import org.prgms.locomocoserver.chat.dto.ChatMessageDto; import org.prgms.locomocoserver.chat.dto.ChatRoomDto; import org.prgms.locomocoserver.chat.dto.request.ChatActivityRequestDto; @@ -23,16 +13,16 @@ import org.prgms.locomocoserver.chat.exception.ChatException; import org.prgms.locomocoserver.global.TestFactory; import org.prgms.locomocoserver.image.domain.ImageRepository; -import org.prgms.locomocoserver.mogakkos.application.MogakkoLikeService; import org.prgms.locomocoserver.mogakkos.application.MogakkoParticipationService; -import org.prgms.locomocoserver.mogakkos.domain.location.MogakkoLocation; -import org.prgms.locomocoserver.mogakkos.domain.location.MogakkoLocationRepository; -import org.prgms.locomocoserver.mogakkos.domain.vo.AddressInfo; -import org.prgms.locomocoserver.mogakkos.dto.LocationInfoDto; import org.prgms.locomocoserver.mogakkos.application.MogakkoService; import org.prgms.locomocoserver.mogakkos.domain.Mogakko; import org.prgms.locomocoserver.mogakkos.domain.MogakkoRepository; +import org.prgms.locomocoserver.mogakkos.domain.location.MogakkoLocation; +import org.prgms.locomocoserver.mogakkos.domain.location.MogakkoLocationRepository; +import org.prgms.locomocoserver.mogakkos.domain.participants.Participant; import org.prgms.locomocoserver.mogakkos.domain.participants.ParticipantRepository; +import org.prgms.locomocoserver.mogakkos.domain.vo.AddressInfo; +import org.prgms.locomocoserver.mogakkos.dto.LocationInfoDto; import org.prgms.locomocoserver.mogakkos.dto.request.MogakkoCreateRequestDto; import org.prgms.locomocoserver.mogakkos.dto.request.ParticipationRequestDto; import org.prgms.locomocoserver.mogakkos.dto.response.MogakkoCreateResponseDto; @@ -43,8 +33,17 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.DefaultTransactionDefinition; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; + @SpringBootTest class ChatRoomServiceTest { @@ -61,8 +60,6 @@ class ChatRoomServiceTest { @Autowired private MongoChatMessageService mongoChatMessageService; @Autowired - private MogakkoParticipationService mogakkoParticipationService; - @Autowired private ChatActivityService chatActivityService; @Autowired private MogakkoRepository mogakkoRepository; @@ -95,21 +92,21 @@ void success_enter_chat_room_as_participant() { // given List dummyUsers = new ArrayList<>(); IntStream.rangeClosed(0, 2).forEach(i -> dummyUsers.add( - User.builder().nickname("name" + i).email(i + "email@gmail.com").birth(LocalDate.EPOCH) - .temperature(36.5).provider("kakao").gender(Gender.MALE).build())); + User.builder().nickname("name" + i).email(i + "email@gmail.com").birth(LocalDate.EPOCH) + .temperature(36.5).provider("kakao").gender(Gender.MALE).build())); userRepository.saveAll(dummyUsers); AddressInfo addressInfo = AddressInfo.builder().address("Martin Garrix").city("Carry You") - .build(); + .build(); MogakkoLocation mogakkoLocation = MogakkoLocation.builder().addressInfo(addressInfo) - .latitude(10.233214).longitude(23.312314).build(); + .latitude(10.233214).longitude(23.312314).build(); MogakkoCreateResponseDto responseDto = mogakkoService.save( - new MogakkoCreateRequestDto(dummyUsers.get(0).getId(), "title", - LocationInfoDto.create(mogakkoLocation), - LocalDateTime.now(), LocalDateTime.now().plusHours(2), - LocalDateTime.now().plusHours(1), - 10, "", List.of())); + new MogakkoCreateRequestDto(dummyUsers.get(0).getId(), "title", + LocationInfoDto.create(mogakkoLocation), + LocalDateTime.now(), LocalDateTime.now().plusHours(2), + LocalDateTime.now().plusHours(1), + 10, "", List.of())); Mogakko mogakko = mogakkoService.getByIdNotDeleted(responseDto.id()); // when @@ -120,7 +117,7 @@ void success_enter_chat_room_as_participant() { TransactionStatus status = tx.getTransaction(new DefaultTransactionDefinition()); ChatRoom chatRoom = chatRoomRepository.findByIdAndDeletedAtIsNull( - mogakko.getChatRoom().getId()).orElseThrow(() -> new ChatException(ChatErrorType.CHATROOM_NOT_FOUND)); + mogakko.getChatRoom().getId()).orElseThrow(() -> new ChatException(ChatErrorType.CHATROOM_NOT_FOUND)); assertThat(chatRoom.getMogakko().getId()).isEqualTo(mogakko.getId()); assertThat(chatRoom.getCreator().getId()).isEqualTo(dummyUsers.get(0).getId()); @@ -140,16 +137,24 @@ void success_get_all_chat_rooms_partial_unread_messages() { Mogakko mogakko = TestFactory.createMogakko(user); mogakko = mogakkoRepository.save(mogakko); ChatRoom chatRoom1 = TestFactory.createChatRoom(user, mogakko); - chatRoomRepository.save(chatRoom1); - mogakkoParticipationService.participate(mogakko.getId(), new ParticipationRequestDto(user1.getId(), null, null)); + chatRoom1 = chatRoomRepository.save(chatRoom1); + participantRepository.save(new Participant(null, null, user, mogakko)); + ChatParticipant chatParticipant = chatParticipantRepository.save(new ChatParticipant(user, chatRoom1)); + chatRoom1.addChatParticipant(chatParticipant); - mongoChatMessageService.createChatRoom(chatRoom1.getId()); ChatMessageDto messageDto1 = mongoChatMessageService.saveChatMessage(chatRoom1.getId(), new ChatMessageRequestDto(chatRoom1.getId(), user.getId(), "test1", null)); ChatMessageDto messageDto2 = mongoChatMessageService.saveChatMessage(chatRoom1.getId(), new ChatMessageRequestDto(chatRoom1.getId(), user.getId(), "test2", null)); // when - chatActivityService.updateLastReadMessage(chatRoom1.getId(), new ChatActivityRequestDto(user1.getId(), messageDto1.chatMessageId())); - List chatRoomDtos = chatRoomService.getAllChatRoom(user1.getId(), Long.MAX_VALUE, 10); + chatParticipant.updateLastReadMessageId(messageDto1.chatMessageId()); + chatParticipantRepository.save(chatParticipant); + System.out.println("-------------" + chatParticipant.getLastReadMessageId()); + List chatRoomDtos = chatRoomService.getAllChatRoom(user.getId(), LocalDateTime.now().toString(), 10); + System.out.println(chatRoomDtos.get(0).updatedAt() + " " + LocalDateTime.now().toString()); + + for(int i=0; i chatRooms = chatRoomCustomRepository.findByParticipantsId(user1.getId(), Long.MAX_VALUE, 10); + List chatRooms = chatRoomCustomRepository.findByParticipantsId(user1.getId(), LocalDateTime.now().toString(), 10); ChatRoomDto.of(chatRooms.get(0), 0,null); // then diff --git a/src/test/java/org/prgms/locomocoserver/user/application/UserServiceTest.java b/src/test/java/org/prgms/locomocoserver/user/application/UserServiceTest.java index c5d86959..16635d5d 100644 --- a/src/test/java/org/prgms/locomocoserver/user/application/UserServiceTest.java +++ b/src/test/java/org/prgms/locomocoserver/user/application/UserServiceTest.java @@ -211,7 +211,7 @@ void deleteUser_success() { .extracting(participant -> participant.getId()) .doesNotContain(user.getId()); - List chatRooms = chatRoomCustomRepository.findByParticipantsId(user.getId(), 0L, 10); + List chatRooms = chatRoomCustomRepository.findByParticipantsId(user.getId(), LocalDateTime.now().toString(), 10); assertThat(chatRooms).isEmpty(); } From da2bf54cd8bd84f1f1b04762e20504d5449e8451 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Tue, 15 Oct 2024 20:09:49 +0900 Subject: [PATCH 07/34] =?UTF-8?q?refactor=20#258=20:=20chatMessage=20?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=20=EC=8B=9C=20objectId=20=EA=B8=B0=EC=A4=80?= =?UTF-8?q?=20=EC=A0=95=EB=A0=AC=20=EB=B0=8F=20=EC=BB=A4=EC=84=9C=20?= =?UTF-8?q?=EA=B0=92=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatActivityService.java | 3 ++- .../domain/mongo/ChatMessageMongoCustomRepository.java | 7 ++++++- .../chat/domain/mongo/ChatMessageMongoRepository.java | 5 ++++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java index e1d04e5e..a93fde1a 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java @@ -1,6 +1,7 @@ package org.prgms.locomocoserver.chat.application; import lombok.RequiredArgsConstructor; +import org.bson.types.ObjectId; import org.prgms.locomocoserver.chat.domain.ChatParticipant; import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoRepository; import org.prgms.locomocoserver.chat.domain.querydsl.ChatParticipantCustomRepository; @@ -29,6 +30,6 @@ public int unReadMessageCount(Long roomId, String lastReadMsgId) { if (lastReadMsgId == null) { return 0; } - return (int) chatMessageMongoRepository.countByChatRoomIdAndIdGreaterThan(roomId.toString(), lastReadMsgId); + return (int) chatMessageMongoRepository.countByChatRoomIdAndIdGreaterThan(roomId.toString(), new ObjectId(lastReadMsgId)); } } diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java index 6fcd5a41..cae4fd5a 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java @@ -1,6 +1,8 @@ package org.prgms.locomocoserver.chat.domain.mongo; import lombok.RequiredArgsConstructor; +import org.bson.types.ObjectId; +import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; @@ -8,6 +10,7 @@ import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; +import java.util.Date; import java.util.List; @Repository @@ -18,9 +21,11 @@ public class ChatMessageMongoCustomRepository { @Transactional(readOnly = true) public List findAllChatMessages(Long roomId, String cursorValue, int pageSize) { + ObjectId cursor = cursorValue == null ? new ObjectId(new Date(Long.MAX_VALUE)) : new ObjectId(cursorValue); Query query = new Query(); + query.with(Sort.by(Sort.Direction.DESC, "_id")); query.addCriteria(Criteria.where("chatRoomId").is(roomId.toString()) - .and("createdAt").lt(LocalDateTime.parse(cursorValue))); + .and("_id").lt(cursor)); query.limit(pageSize); return mongoTemplate.find(query, ChatMessageMongo.class); diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoRepository.java index 10af5474..97080086 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoRepository.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoRepository.java @@ -1,5 +1,6 @@ package org.prgms.locomocoserver.chat.domain.mongo; +import org.bson.types.ObjectId; import org.springframework.data.mongodb.repository.MongoRepository; import java.time.LocalDateTime; @@ -10,7 +11,9 @@ public interface ChatMessageMongoRepository extends MongoRepository findTopByChatRoomIdOrderByCreatedAtDesc(String chatRoomId); - long countByChatRoomIdAndIdGreaterThan(String chatRoomId, String lastReadMsgId); + List findAllByChatRoomId(String chatRoomId); + + long countByChatRoomIdAndIdGreaterThan(String chatRoomId, ObjectId lastReadMsgId); void deleteByChatRoomId(String chatRoomId); } From bbe8c1df14a897280382de3164ae68fa9cb0299e Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Tue, 15 Oct 2024 20:14:18 +0900 Subject: [PATCH 08/34] =?UTF-8?q?test=20#258=20:=20chatMessage=20=EC=A1=B0?= =?UTF-8?q?=ED=9A=8C=20=EC=8B=9C=20objectId=20=EA=B8=B0=EC=A4=80=20?= =?UTF-8?q?=EC=A0=95=EB=A0=AC=20=EB=B0=8F=20=EC=BB=A4=EC=84=9C=EA=B0=92=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatRoomServiceTest.java | 4 ++- .../application/MongoChatServiceTest.java | 34 +++++++++++++------ 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java b/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java index f0b97496..7cd83ab7 100644 --- a/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java +++ b/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.prgms.locomocoserver.chat.domain.*; +import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoRepository; import org.prgms.locomocoserver.chat.dto.ChatMessageDto; import org.prgms.locomocoserver.chat.dto.ChatRoomDto; import org.prgms.locomocoserver.chat.dto.request.ChatActivityRequestDto; @@ -60,7 +61,7 @@ class ChatRoomServiceTest { @Autowired private MongoChatMessageService mongoChatMessageService; @Autowired - private ChatActivityService chatActivityService; + private ChatMessageMongoRepository chatMessageMongoRepository; @Autowired private MogakkoRepository mogakkoRepository; @Autowired @@ -84,6 +85,7 @@ void tearDown() { mogakkoRepository.deleteAll(); userRepository.deleteAll(); imageRepository.deleteAll(); + chatMessageMongoRepository.deleteAll(); } @Test diff --git a/src/test/java/org/prgms/locomocoserver/chat/application/MongoChatServiceTest.java b/src/test/java/org/prgms/locomocoserver/chat/application/MongoChatServiceTest.java index 880872eb..52eadfb0 100644 --- a/src/test/java/org/prgms/locomocoserver/chat/application/MongoChatServiceTest.java +++ b/src/test/java/org/prgms/locomocoserver/chat/application/MongoChatServiceTest.java @@ -7,6 +7,7 @@ import org.prgms.locomocoserver.chat.domain.ChatRoom; import org.prgms.locomocoserver.chat.domain.ChatRoomRepository; import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongo; +import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoRepository; import org.prgms.locomocoserver.chat.dto.ChatMessageDto; import org.prgms.locomocoserver.chat.dto.request.ChatMessageRequestDto; import org.prgms.locomocoserver.global.TestFactory; @@ -20,14 +21,17 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.transaction.annotation.Transactional; +import org.testcontainers.shaded.org.apache.commons.lang3.ObjectUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import java.time.LocalDateTime; import java.util.Base64; import java.util.List; +import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @@ -57,6 +61,8 @@ class MongoChatServiceTest { MogakkoRepository mogakkoRepository; @Autowired ChatParticipantRepository chatParticipantRepository; + @Autowired + ChatMessageMongoRepository chatMessageMongoRepository; private User creator; private ChatRoom chatRoom; @@ -70,6 +76,7 @@ void setUp() { userRepository.deleteAll(); imageRepository.deleteAll(); categoryRepository.deleteAll(); + chatMessageMongoRepository.deleteAll(); User sender = TestFactory.createUser(); imageRepository.save(sender.getProfileImage()); @@ -82,6 +89,17 @@ void setUp() { chatParticipantRepository.save(TestFactory.createChatParticipant(sender, chatRoom)); } + @AfterAll + void tearDown() { + chatParticipantRepository.deleteAll(); + chatRoomRepository.deleteAll(); + mogakkoRepository.deleteAll(); + userRepository.deleteAll(); + imageRepository.deleteAll(); + categoryRepository.deleteAll(); + chatMessageMongoRepository.deleteAll(); + } + @Test @Order(1) @DisplayName("채팅방 입장 메시지를 저장할 수 있다.") @@ -92,10 +110,10 @@ void saveEnterMessage() { // when mongoChatMessageService.saveEnterMessage(roomId, creator); - boolean collectionExists = mongoTemplate.collectionExists("chat_messages_" + roomId); + Optional chatMessage = chatMessageMongoRepository.findTopByChatRoomIdOrderByCreatedAtDesc(roomId.toString()); // then - assertThat(collectionExists).isTrue(); + assertThat(chatMessage).isNotEmpty(); } @Test @@ -106,8 +124,7 @@ void saveChatMessage() { // given Long roomId = chatRoom.getId(); Long senderId = creator.getId(); - String collectionName = mongoChatMessageService.getChatRoomName(roomId); - long beforeMessageCount = mongoTemplate.getCollection(collectionName).countDocuments(); + long beforeMessageCount = chatMessageMongoRepository.findAllByChatRoomId(roomId.toString()).size(); byte[] byteCode = imageToByteArray("src/test/resources/스누피4.jpeg"); String imageBase64 = Base64.getEncoder().encodeToString(byteCode); @@ -117,15 +134,13 @@ void saveChatMessage() { List imageUrls = chatImageService.create(requestDto); mongoChatMessageService.saveChatMessageWithImage(roomId, imageUrls, requestDto); - boolean collectionExists = mongoTemplate.collectionExists(collectionName); - long messageCount = mongoTemplate.getCollection(collectionName).countDocuments(); + long messageCount = chatMessageMongoRepository.findAllByChatRoomId(roomId.toString()).size(); - List messages = mongoTemplate.findAll(ChatMessageMongo.class, collectionName); + List messages = chatMessageMongoRepository.findAllByChatRoomId(roomId.toString()); assertThat(messages).isNotEmpty(); ChatMessageMongo lastMessage = messages.get(messages.size() - 1); // then - assertThat(collectionExists).isTrue(); assertThat(messageCount).isEqualTo(beforeMessageCount + 1); assertThat(lastMessage.getImageUrls().size()).isEqualTo(1); assertThat(lastMessage.getImageUrls().get(0).contains(".jpeg")).isTrue(); @@ -137,10 +152,9 @@ void saveChatMessage() { void getAllChatMessages() { // given Long roomId = chatRoom.getId(); - String collectionName = mongoChatMessageService.getChatRoomName(roomId); // when - List chatMessageMongoList = mongoChatMessageService.getAllChatMessages(roomId, "null", 10); + List chatMessageMongoList = mongoChatMessageService.getAllChatMessages(roomId, null, 10); assertThat(chatMessageMongoList.size()).isEqualTo(2); String cursor = chatMessageMongoList.get(1).chatMessageId(); From 15c22d9ee5615a3e8bc0c43de1b8f6f09e317c80 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Tue, 15 Oct 2024 20:14:35 +0900 Subject: [PATCH 09/34] =?UTF-8?q?chore=20#258=20:=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../application/MogakkoParticipationTest.java | 79 +++++++++---------- 1 file changed, 39 insertions(+), 40 deletions(-) diff --git a/src/test/java/org/prgms/locomocoserver/mogakkos/application/MogakkoParticipationTest.java b/src/test/java/org/prgms/locomocoserver/mogakkos/application/MogakkoParticipationTest.java index ef80cbe3..7648d0f1 100644 --- a/src/test/java/org/prgms/locomocoserver/mogakkos/application/MogakkoParticipationTest.java +++ b/src/test/java/org/prgms/locomocoserver/mogakkos/application/MogakkoParticipationTest.java @@ -1,20 +1,6 @@ package org.prgms.locomocoserver.mogakkos.application; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.within; -import static org.prgms.locomocoserver.global.TestFactory.createMogakko; -import static org.prgms.locomocoserver.global.TestFactory.createUser; - import ch.qos.logback.core.util.ExecutorServiceUtil; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.IntStream; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.bson.assertions.Assertions; import org.junit.jupiter.api.AfterEach; @@ -40,6 +26,19 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.*; +import static org.prgms.locomocoserver.global.TestFactory.createMogakko; +import static org.prgms.locomocoserver.global.TestFactory.createUser; + @SpringBootTest class MogakkoParticipationTest { @@ -75,14 +74,14 @@ void setUp() { userRepository.save(testCreator); Long savedMogakkoId = mogakkoService.save( - new MogakkoCreateRequestDto(testCreator.getId(), testMogakko.getTitle(), - new LocationInfoDto("", 127.52d, 27.8621d, null, null), testMogakko.getStartTime(), - testMogakko.getEndTime(), testMogakko.getDeadline(), - testMogakko.getMaxParticipants(), - testMogakko.getContent(), Collections.EMPTY_LIST)).id(); + new MogakkoCreateRequestDto(testCreator.getId(), testMogakko.getTitle(), + new LocationInfoDto("", 127.52d, 27.8621d, null, null), testMogakko.getStartTime(), + testMogakko.getEndTime(), testMogakko.getDeadline(), + testMogakko.getMaxParticipants(), + testMogakko.getContent(), Collections.EMPTY_LIST)).id(); testMogakko = mogakkoRepository.findById(savedMogakkoId) - .orElseThrow(() -> new RuntimeException("mogakko not found")); + .orElseThrow(() -> new RuntimeException("mogakko not found")); } @AfterEach @@ -106,7 +105,7 @@ void fail_participate_in_mogakko_already_belong_to() { // when then assertThatThrownBy(() -> mogakkoParticipationService.participate(mogakkoId, requestDto)) - .isInstanceOf(RuntimeException.class).hasMessageContaining("이미 참여한 유저입니다."); // TODO: 참여 예외 반환 + .isInstanceOf(RuntimeException.class).hasMessageContaining("이미 참여한 유저입니다."); // TODO: 참여 예외 반환 } @Test @@ -117,11 +116,11 @@ void fail_cancel_to_participate() { Long creatorId = testCreator.getId(); ThrowingCallable cancelFunc = () -> mogakkoParticipationService.cancel( - mogakkoId, creatorId); + mogakkoId, creatorId); // when then assertThatThrownBy(cancelFunc).isInstanceOf(RuntimeException.class) - .hasMessageContaining("모각코 생성자가 참여를 취소할 수 없습니다."); + .hasMessageContaining("모각코 생성자가 참여를 취소할 수 없습니다."); } @Test @@ -138,7 +137,7 @@ void fail_participate_in_mogakko_when_it_is_full() throws Exception { users.forEach(u -> imageRepository.save(u.getProfileImage())); userRepository.saveAll(users); List participationRequestDtos = users.stream() - .map(u -> new ParticipationRequestDto(u.getId(), null, null)).toList(); + .map(u -> new ParticipationRequestDto(u.getId(), null, null)).toList(); CountDownLatch countDownLatch = new CountDownLatch(usersNum); @@ -146,17 +145,17 @@ void fail_participate_in_mogakko_when_it_is_full() throws Exception { AtomicInteger overCount = new AtomicInteger(); participationRequestDtos.forEach(dto -> - threadPoolExecutor.execute( - () -> { - try { - mogakkoParticipationService.participate(mogakkoId, dto); - } catch (Exception e) { - log.info("예외 발생"); - overCount.getAndIncrement(); - } finally { - countDownLatch.countDown(); - } - }) + threadPoolExecutor.execute( + () -> { + try { + mogakkoParticipationService.participate(mogakkoId, dto); + } catch (Exception e) { + log.info("예외 발생"); + overCount.getAndIncrement(); + } finally { + countDownLatch.countDown(); + } + }) ); countDownLatch.await(5000, TimeUnit.MILLISECONDS); @@ -171,14 +170,14 @@ void success_update_info() { double latitude = 27.12345678999999d; double longitude = 127.12423d; ParticipationRequestDto requestDto = new ParticipationRequestDto(testCreator.getId(), - longitude, latitude); + longitude, latitude); // when mogakkoParticipationService.update(testMogakko.getId(), requestDto); // then Participant participant = participantRepository.findByMogakkoIdAndUserId( - testMogakko.getId(), testCreator.getId()).orElseThrow(RuntimeException::new); + testMogakko.getId(), testCreator.getId()).orElseThrow(RuntimeException::new); double columnPointLimit = 0.0000000001d; assertThat(participant.getLongitude()).isEqualTo(longitude, within(columnPointLimit)); @@ -212,7 +211,7 @@ void success_cancel_to_participate_in_mogakko() throws Exception { // then List participants = participantRepository.findAllByMogakkoId( - testMogakko.getId()); + testMogakko.getId()); assertThat(participants).hasSize(1); } @@ -222,9 +221,9 @@ void success_cancel_to_participate_in_mogakko() throws Exception { void success_check_whether_user_participate_in_mogakko() { // when ParticipationCheckingDto checkedTrueDto = mogakkoParticipationService.check(testMogakko.getId(), - testCreator.getId()); + testCreator.getId()); ParticipationCheckingDto checkedFalseDto = mogakkoParticipationService.check(testMogakko.getId(), - testCreator.getId() + 1L); + testCreator.getId() + 1L); // then assertThat(checkedTrueDto.isParticipated()).isTrue(); From fb127243da61f22694944ff3cd5f1b0a333e10b5 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:13:27 +0900 Subject: [PATCH 10/34] =?UTF-8?q?feat=20#258=20:=20mongoTemplate=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EC=82=AC=EC=9A=A9=ED=95=A0=20=EB=8D=B0=EC=9D=B4?= =?UTF-8?q?=ED=84=B0=20=EA=B0=9D=EC=B2=B4=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../locomocoserver/chat/dao/ChatActivityDao.java | 15 +++++++++++++++ .../chat/dao/ChatActivityRequestDao.java | 9 +++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/main/java/org/prgms/locomocoserver/chat/dao/ChatActivityDao.java create mode 100644 src/main/java/org/prgms/locomocoserver/chat/dao/ChatActivityRequestDao.java diff --git a/src/main/java/org/prgms/locomocoserver/chat/dao/ChatActivityDao.java b/src/main/java/org/prgms/locomocoserver/chat/dao/ChatActivityDao.java new file mode 100644 index 00000000..3590d4e4 --- /dev/null +++ b/src/main/java/org/prgms/locomocoserver/chat/dao/ChatActivityDao.java @@ -0,0 +1,15 @@ +package org.prgms.locomocoserver.chat.dao; + +import org.bson.types.ObjectId; + +import java.time.LocalDateTime; + +public record ChatActivityDao( + String unReadMsgCnt, + String chatRoomId, + ObjectId chatMessageId, + String senderId, + String message, + LocalDateTime createdAt +) { +} diff --git a/src/main/java/org/prgms/locomocoserver/chat/dao/ChatActivityRequestDao.java b/src/main/java/org/prgms/locomocoserver/chat/dao/ChatActivityRequestDao.java new file mode 100644 index 00000000..af4c7b87 --- /dev/null +++ b/src/main/java/org/prgms/locomocoserver/chat/dao/ChatActivityRequestDao.java @@ -0,0 +1,9 @@ +package org.prgms.locomocoserver.chat.dao; + +import org.bson.types.ObjectId; + +public record ChatActivityRequestDao( + String chatRoomId, + ObjectId lastReadMsgId +) { +} From 50dd23dccb885f785551805901d74512a5f1d7a8 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:14:23 +0900 Subject: [PATCH 11/34] =?UTF-8?q?feat=20#258=20:=20chatRoom=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D=20=EC=A1=B0=ED=9A=8C=20=EC=8B=9C=20=EB=A7=88=EC=A7=80?= =?UTF-8?q?=EB=A7=89=20=EB=A9=94=EC=8B=9C=EC=A7=80=20=EC=A0=95=EB=B3=B4=20?= =?UTF-8?q?=ED=95=84=EC=9A=94=ED=95=9C=20=ED=95=84=EB=93=9C=EB=A7=8C=20?= =?UTF-8?q?=EA=B5=AC=EC=84=B1=ED=95=9C=20dto=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/dto/ChatMessageBriefDto.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/main/java/org/prgms/locomocoserver/chat/dto/ChatMessageBriefDto.java diff --git a/src/main/java/org/prgms/locomocoserver/chat/dto/ChatMessageBriefDto.java b/src/main/java/org/prgms/locomocoserver/chat/dto/ChatMessageBriefDto.java new file mode 100644 index 00000000..b1044acc --- /dev/null +++ b/src/main/java/org/prgms/locomocoserver/chat/dto/ChatMessageBriefDto.java @@ -0,0 +1,15 @@ +package org.prgms.locomocoserver.chat.dto; + +import java.time.LocalDateTime; + +public record ChatMessageBriefDto( + String chatRoomId, + String chatMessageId, + String senderId, + String message, + LocalDateTime createdAt +) { + public static ChatMessageBriefDto of(String chatRoomId, String chatMessageId, String senderId, String message, LocalDateTime createdAt) { + return new ChatMessageBriefDto(chatRoomId, chatMessageId, senderId, message, createdAt); + } +} From d381eed16f6181c875009f110af2b672225efade Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:16:44 +0900 Subject: [PATCH 12/34] =?UTF-8?q?feat=20#258=20:=20userId=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D=EC=9C=BC=EB=A1=9C=20=ED=95=9C=EB=B2=88=EC=97=90=20?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=ED=95=98=EB=8A=94=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../org/prgms/locomocoserver/user/domain/UserRepository.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/prgms/locomocoserver/user/domain/UserRepository.java b/src/main/java/org/prgms/locomocoserver/user/domain/UserRepository.java index 0a3285d9..76eec69f 100644 --- a/src/main/java/org/prgms/locomocoserver/user/domain/UserRepository.java +++ b/src/main/java/org/prgms/locomocoserver/user/domain/UserRepository.java @@ -14,4 +14,5 @@ public interface UserRepository extends JpaRepository { Optional findByNicknameAndDeletedAtIsNull(String nickname); @Query("SELECT u FROM User u WHERE u.id IN (SELECT p.user.id FROM Participant p WHERE p.mogakko = :mogakko)") List findAllParticipantsByMogakko(Mogakko mogakko); + List findByIdIn(List ids); } From bfdb9dd93f5a1c741a74fb4e219fb71dcbdd380e Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:17:32 +0900 Subject: [PATCH 13/34] =?UTF-8?q?refactor=20#258=20:=20ChatRoomDto=20?= =?UTF-8?q?=EB=B0=98=ED=99=98=20=ED=98=95=ED=83=9C=20=EB=A9=94=EC=8B=9C?= =?UTF-8?q?=EC=A7=80=20=EC=A0=95=EB=B3=B4=EC=99=80=20=EC=9C=A0=EC=A0=80=20?= =?UTF-8?q?=EC=A0=95=EB=B3=B4=20=EA=B0=9D=EC=B2=B4=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../org/prgms/locomocoserver/chat/dto/ChatRoomDto.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/dto/ChatRoomDto.java b/src/main/java/org/prgms/locomocoserver/chat/dto/ChatRoomDto.java index db800187..3c59d9a2 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/dto/ChatRoomDto.java +++ b/src/main/java/org/prgms/locomocoserver/chat/dto/ChatRoomDto.java @@ -12,9 +12,10 @@ public record ChatRoomDto( int unReadMsgCnt, LocalDateTime createdAt, LocalDateTime updatedAt, - ChatMessageDto lastMessage + ChatMessageBriefDto lastMessage, + ChatUserInfo userInfo ) { - public static ChatRoomDto of(ChatRoom chatRoom, int unReadMsgCnt, ChatMessageDto lastMessage) { - return new ChatRoomDto(chatRoom.getId(), chatRoom.getMogakko().getId(), chatRoom.getName(), chatRoom.getChatParticipants().size(), unReadMsgCnt, chatRoom.getCreatedAt(), chatRoom.getUpdatedAt(), lastMessage); + public static ChatRoomDto of(ChatRoom chatRoom, int unReadMsgCnt, ChatMessageBriefDto lastMessage, ChatUserInfo chatUserInfo) { + return new ChatRoomDto(chatRoom.getId(), chatRoom.getMogakko().getId(), chatRoom.getName(), chatRoom.getChatParticipants().size(), unReadMsgCnt, chatRoom.getCreatedAt(), chatRoom.getUpdatedAt(), lastMessage, chatUserInfo); } } From 7862625df1087284b67fa41f6bc87641e7006237 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:18:31 +0900 Subject: [PATCH 14/34] =?UTF-8?q?feat=20#258=20:=20chatRoomId=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D=EC=9C=BC=EB=A1=9C=20=EB=A7=88=EC=A7=80=EB=A7=89=20?= =?UTF-8?q?=EB=A9=94=EC=8B=9C=EC=A7=80=20=EC=A1=B0=ED=9A=8C=20=ED=95=9C?= =?UTF-8?q?=EB=B2=88=EC=97=90=20=EA=B0=80=EC=A0=B8=EC=98=A4=EB=8A=94=20?= =?UTF-8?q?=EC=BF=BC=EB=A6=AC=20=EA=B5=AC=ED=98=84=20=EB=B0=8F=20unReadMsg?= =?UTF-8?q?=20=EA=B0=9C=EC=88=98=20=EC=A1=B0=ED=9A=8C=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ChatMessageMongoCustomRepository.java | 84 ++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java index cae4fd5a..998e3bfc 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java @@ -1,17 +1,24 @@ package org.prgms.locomocoserver.chat.domain.mongo; +import com.mongodb.client.model.Filters; import lombok.RequiredArgsConstructor; import org.bson.types.ObjectId; +import org.prgms.locomocoserver.chat.dao.ChatActivityDao; +import org.prgms.locomocoserver.chat.dao.ChatActivityRequestDao; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; -import java.time.LocalDateTime; import java.util.Date; import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; @Repository @RequiredArgsConstructor @@ -30,4 +37,79 @@ public List findAllChatMessages(Long roomId, String cursorValu return mongoTemplate.find(query, ChatMessageMongo.class); } + + @Transactional(readOnly = true) + public List findLastMessagesAndUnReadMsgCount(List chatRoomInfoDtos) { + // 1. 채팅방 roomId 목록 생성 + List chatRoomIds = chatRoomInfoDtos.stream() + .map(dao -> dao.chatRoomId().toString()) + .collect(Collectors.toList()); + + // 2. 채팅방 필터링 (roomId 기반) + AggregationOperation matchChatRooms = Aggregation.match(Criteria.where("chatRoomId").in(chatRoomIds)); + + // 3. 메시지 시간 순으로 정렬 (최신 메시지가 상단에 오도록) + AggregationOperation sortMessagesByCreatedAtDesc = Aggregation.sort(Sort.by(Sort.Direction.DESC, "createdAt")); + + // 4. 각 채팅방별로 마지막 메시지를 그룹화하고 필요한 필드 선택 + AggregationOperation groupLastMessage = Aggregation.group("chatRoomId") + .first("chatRoomId").as("chatRoomId") // 채팅방 ID 가져오기 + .first("senderId").as("senderId") // 마지막 메시지 보낸 사람 + .first("message").as("message") // 마지막 메시지 내용 + .first("createdAt").as("createdAt") // 마지막 메시지 시간 + .first("_id").as("chatMessageId"); // 마지막 메시지의 MongoDB _id + + // 5. 필요 필드만 선택하는 project 단계 추가 + AggregationOperation projectFields = Aggregation.project() + .and("chatRoomId").as("chatRoomId") + .and("senderId").as("senderId") + .and("message").as("message") + .and("createdAt").as("createdAt") + .and("chatMessageId").as("chatMessageId"); + + // 6. Aggregation Pipeline 생성 (마지막 메시지만 가져옴) + Aggregation aggregation = Aggregation.newAggregation( + matchChatRooms, // roomId로 필터링 + sortMessagesByCreatedAtDesc, // 시간순 정렬 + groupLastMessage, // 각 채팅방별 마지막 메시지 그룹화 + projectFields // 필요한 필드만 선택 + ); + + // 7. Aggregation 결과 실행 + System.out.println("Raw Aggregation Results: " + mongoTemplate.aggregate(aggregation, "chat_messages", Map.class).getMappedResults()); + AggregationResults aggregationResults = mongoTemplate.aggregate(aggregation, "chat_messages", ChatActivityDao.class); + System.out.println("Aggregation Results: " + aggregationResults.getMappedResults()); + + // 8. 마지막 메시지 결과 반환 + List lastMessages = aggregationResults.getMappedResults(); + + // 9. 읽지 않은 메시지 수 계산을 위한 roomId와 lastReadMsgId 맵 생성 + Map lastReadMessageIdMap = chatRoomInfoDtos.stream() + .filter(dao -> dao.lastReadMsgId() != null) + .collect(Collectors.toMap( + dao -> dao.chatRoomId().toString(), + dao -> dao.lastReadMsgId() + )); + + // 10. 읽지 않은 메시지 수를 가져오기 위한 쿼리 생성 + List unreadCounts = lastMessages.stream() + .map(chatActivityDao -> { + String chatRoomId = chatActivityDao.chatRoomId(); // chatRoomId 가져오기 + ObjectId lastReadMsgId = lastReadMessageIdMap.get(chatRoomId); // lastReadMsgId 가져오기 + + // 11. unread 메시지 수 계산 쿼리 + long unreadCount = mongoTemplate.getCollection("chat_messages").countDocuments(Filters.and( + Filters.eq("chatRoomId", chatRoomId), + Filters.gt("_id", lastReadMsgId) + )); + + // 12. 읽지 않은 메시지 수와 마지막 메시지 결합 + return new ChatActivityDao(String.valueOf(unreadCount), chatActivityDao.chatRoomId(), chatActivityDao.chatMessageId(), chatActivityDao.senderId(), chatActivityDao.message(), chatActivityDao.createdAt()); + }) + .collect(Collectors.toList()); + + // 13. 결과 반환 + return unreadCounts; + } + } From 7dae2fb67fc0e0a74d98d518afc4a517c9f3caa0 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:23:45 +0900 Subject: [PATCH 15/34] =?UTF-8?q?chore=20#258=20:=20=EB=94=94=EB=B2=84?= =?UTF-8?q?=EA=B9=85=20=EC=BD=94=EB=93=9C=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/domain/mongo/ChatMessageMongoCustomRepository.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java index 998e3bfc..9387c1ae 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java @@ -76,9 +76,7 @@ public List findLastMessagesAndUnReadMsgCount(List aggregationResults = mongoTemplate.aggregate(aggregation, "chat_messages", ChatActivityDao.class); - System.out.println("Aggregation Results: " + aggregationResults.getMappedResults()); // 8. 마지막 메시지 결과 반환 List lastMessages = aggregationResults.getMappedResults(); From 174d3f83d72c58fb72dbd9eeedfaf0c6197d61e4 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:24:22 +0900 Subject: [PATCH 16/34] =?UTF-8?q?refactor=20#258=20:=20=EB=A6=AC=ED=8C=A9?= =?UTF-8?q?=ED=86=A0=EB=A7=81=EB=90=9C=20=EB=A0=88=ED=8F=AC=EC=A7=80?= =?UTF-8?q?=ED=86=A0=EB=A6=AC=20=EB=A9=94=EC=84=9C=EB=93=9C=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatRoomService.java | 67 ++++++++++++++----- 1 file changed, 51 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java index 85d0eb51..8f9e5700 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java @@ -2,37 +2,45 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.bson.types.ObjectId; +import org.prgms.locomocoserver.chat.dao.ChatActivityDao; +import org.prgms.locomocoserver.chat.dao.ChatActivityRequestDao; import org.prgms.locomocoserver.chat.domain.ChatParticipant; -import org.prgms.locomocoserver.chat.domain.ChatParticipantRepository; import org.prgms.locomocoserver.chat.domain.ChatRoom; import org.prgms.locomocoserver.chat.domain.ChatRoomRepository; +import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoCustomRepository; import org.prgms.locomocoserver.chat.domain.querydsl.ChatParticipantCustomRepository; import org.prgms.locomocoserver.chat.domain.querydsl.ChatRoomCustomRepository; +import org.prgms.locomocoserver.chat.dto.ChatMessageBriefDto; import org.prgms.locomocoserver.chat.dto.ChatMessageDto; import org.prgms.locomocoserver.chat.dto.ChatRoomDto; +import org.prgms.locomocoserver.chat.dto.ChatUserInfo; import org.prgms.locomocoserver.chat.dto.request.ChatCreateRequestDto; import org.prgms.locomocoserver.chat.dto.request.ChatEnterRequestDto; import org.prgms.locomocoserver.chat.dto.request.ChatMessageRequestDto; import org.prgms.locomocoserver.chat.exception.ChatErrorType; import org.prgms.locomocoserver.chat.exception.ChatException; import org.prgms.locomocoserver.user.domain.User; +import org.prgms.locomocoserver.user.domain.UserRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.stream.Collectors; @Slf4j @Service @RequiredArgsConstructor public class ChatRoomService { - private final MongoChatMessageService mongoChatMessageService; private final ChatRoomRepository chatRoomRepository; private final ChatRoomCustomRepository chatRoomCustomRepository; private final ChatParticipantCustomRepository chatParticipantCustomRepository; - private final ChatActivityService chatActivityService; + private final UserRepository userRepository; + private final ChatMessageMongoCustomRepository chatMessageMongoCustomRepository; private final StompChatService stompChatService; private final ChatMessagePolicy chatMessagePolicy; @@ -81,23 +89,37 @@ public ChatMessageDto saveEnterMessage(ChatEnterRequestDto requestDto) { return chatMessagePolicy.saveEnterMessage(requestDto.chatRoomId(), requestDto.participant()); } + @Transactional(readOnly = true) public List getAllChatRoom(Long userId, String cursor, int pageSize) { if (cursor == null) cursor = LocalDateTime.now().toString(); + List chatRooms = chatRoomCustomRepository.findByParticipantsId(userId, cursor, pageSize); - List chatRoomDtos = chatRooms.stream() + List chatActivityRequestDaos = createChatActivityRequestDao(userId, chatRooms); + List lastMessages = chatMessageMongoCustomRepository.findLastMessagesAndUnReadMsgCount(chatActivityRequestDaos); + + Map lastMsgMongoMap = lastMessages.stream() + .collect(Collectors.toMap( + dao -> dao.chatRoomId(), + dao -> dao + )); + + List userIds = createUserIds(lastMessages); + Map userMap = userRepository.findByIdIn(userIds).stream() + .collect(Collectors.toMap(User::getId, user -> user)); + + return chatRooms.stream() .map(chatRoom -> { - ChatMessageDto lastMessageDto = chatMessagePolicy.getLastChatMessage(chatRoom.getId()); - ChatParticipant chatParticipant = getChatParticipant(chatRoom, userId); + ChatActivityDao dao = lastMsgMongoMap.get(chatRoom.getId()); + ChatMessageBriefDto lastMessageDto = ChatMessageBriefDto.of(dao.chatRoomId(), dao.chatMessageId().toString(), dao.senderId(), dao.message(), dao.createdAt()); + User user = userMap.get(Long.parseLong(dao.senderId())); + ChatUserInfo chatUserInfo = user.getDeletedAt() == null ? ChatUserInfo.of(user) : ChatUserInfo.deletedUser(user.getId()); - log.info(chatRoom.getChatParticipants().get(0).getLastReadMessageId()); - int unReadMsgCnt = chatActivityService.unReadMessageCount(chatRoom.getId(), chatParticipant.getLastReadMessageId()); - return ChatRoomDto.of(chatRoom, unReadMsgCnt, lastMessageDto); + return ChatRoomDto.of(chatRoom, Integer.parseInt(dao.unReadMsgCnt()), lastMessageDto, chatUserInfo); }) - .filter(Objects::nonNull) // null인 경우 제외 + .filter(Objects::nonNull) .toList(); - return chatRoomDtos; } @Transactional(readOnly = true) @@ -137,10 +159,23 @@ private boolean isParticipantExist(ChatRoom chatRoom, User user) { .anyMatch(chatParticipant -> chatParticipant.getUser().getId().equals(user.getId())); } - private ChatParticipant getChatParticipant(ChatRoom chatRoom, Long userId) { - return chatRoom.getChatParticipants().stream() - .filter(p -> p.getUser().getId().equals(userId)) - .findFirst() - .orElse(null); + private List createChatActivityRequestDao(Long userId, List chatRooms) { + return chatRooms.stream() + .map(chatRoom -> new ChatActivityRequestDao( + chatRoom.getId().toString(), + chatRoom.getChatParticipants().stream() + .filter(p -> p.getUser().getId().equals(userId)) + .findFirst() + .map(user -> new ObjectId(user.getLastReadMessageId())) + .orElse(null) + )) + .collect(Collectors.toList()); + } + + private List createUserIds(List lastMessages) { + return lastMessages.stream() + .map(dao -> Long.valueOf(dao.senderId())) + .distinct() + .collect(Collectors.toList()); } } From 61f8987c17c31fcf80ac3fd7eebc1148080fd145 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:24:48 +0900 Subject: [PATCH 17/34] =?UTF-8?q?test=20#258=20:=20ChatRoomDto=20=EB=B3=80?= =?UTF-8?q?=ED=98=95=EB=90=9C=20=ED=98=95=ED=83=9C=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/repository/ChatRoomRepositoryTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/prgms/locomocoserver/chat/repository/ChatRoomRepositoryTest.java b/src/test/java/org/prgms/locomocoserver/chat/repository/ChatRoomRepositoryTest.java index feca2061..3dfe260d 100644 --- a/src/test/java/org/prgms/locomocoserver/chat/repository/ChatRoomRepositoryTest.java +++ b/src/test/java/org/prgms/locomocoserver/chat/repository/ChatRoomRepositoryTest.java @@ -6,8 +6,9 @@ import org.prgms.locomocoserver.chat.domain.ChatParticipantRepository; import org.prgms.locomocoserver.chat.domain.ChatRoom; import org.prgms.locomocoserver.chat.domain.ChatRoomRepository; -import org.prgms.locomocoserver.chat.dto.ChatRoomDto; import org.prgms.locomocoserver.chat.domain.querydsl.ChatRoomCustomRepository; +import org.prgms.locomocoserver.chat.dto.ChatRoomDto; +import org.prgms.locomocoserver.chat.dto.ChatUserInfo; import org.prgms.locomocoserver.global.TestFactory; import org.prgms.locomocoserver.image.domain.ImageRepository; import org.prgms.locomocoserver.mogakkos.domain.Mogakko; @@ -85,7 +86,7 @@ void findByParticipantsIdWithJPA() { List chatRooms = chatRoomRepository.findByParticipantsId(user1.getId(), Long.MAX_VALUE, 10); // fetch join X, Transaction X, Lazy Loading assertThrows(LazyInitializationException.class, () -> { - ChatRoomDto.of(chatRooms.get(0), 0, null); + ChatRoomDto.of(chatRooms.get(0), 0, null, ChatUserInfo.of(user1)); }); // then @@ -100,7 +101,7 @@ void findByParticipantsWithQueryDSL() { // when List chatRooms = chatRoomCustomRepository.findByParticipantsId(user1.getId(), LocalDateTime.now().toString(), 10); - ChatRoomDto.of(chatRooms.get(0), 0,null); + ChatRoomDto.of(chatRooms.get(0), 0, null, ChatUserInfo.of(user1)); // then System.out.println("Participants Num : " + chatRooms.size()); From f3f3f66c0150ebed53556962402ae8761faf93ce Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:29:47 +0900 Subject: [PATCH 18/34] =?UTF-8?q?refactor=20#258=20:=20service=20=EB=8B=A8?= =?UTF-8?q?=20map=20=ED=82=A4=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20=ED=83=80?= =?UTF-8?q?=EC=9E=85=20=ED=86=B5=EC=9D=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../locomocoserver/chat/application/ChatRoomService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java index 8f9e5700..e4006e9a 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java @@ -99,9 +99,9 @@ public List getAllChatRoom(Long userId, String cursor, int pageSize List chatActivityRequestDaos = createChatActivityRequestDao(userId, chatRooms); List lastMessages = chatMessageMongoCustomRepository.findLastMessagesAndUnReadMsgCount(chatActivityRequestDaos); - Map lastMsgMongoMap = lastMessages.stream() + Map lastMsgMongoMap = lastMessages.stream() .collect(Collectors.toMap( - dao -> dao.chatRoomId(), + dao -> Long.parseLong(dao.chatRoomId()), dao -> dao )); From 0880bf57c02e575b736f1a397273b2a813ac9300 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:49:07 +0900 Subject: [PATCH 19/34] =?UTF-8?q?refactor=20#258=20:=20image=20fetchJoin?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80=ED=95=9C=20=EB=A9=94=EC=84=9C=EB=93=9C=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/domain/querydsl/UserCustomRepository.java | 2 +- .../user/domain/querydsl/UserCustomRepositoryImpl.java | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/user/domain/querydsl/UserCustomRepository.java b/src/main/java/org/prgms/locomocoserver/user/domain/querydsl/UserCustomRepository.java index 65997f79..74ad1738 100644 --- a/src/main/java/org/prgms/locomocoserver/user/domain/querydsl/UserCustomRepository.java +++ b/src/main/java/org/prgms/locomocoserver/user/domain/querydsl/UserCustomRepository.java @@ -7,7 +7,7 @@ import java.util.Optional; public interface UserCustomRepository { - List findAllById(List userIds); + List findAllWithImageByIdIn(List userIds); List findAllParticipantsByMogakko(Mogakko mogakko); Optional findUserAndImageByUserIdAndDeletedAtIsNull(Long userId); } diff --git a/src/main/java/org/prgms/locomocoserver/user/domain/querydsl/UserCustomRepositoryImpl.java b/src/main/java/org/prgms/locomocoserver/user/domain/querydsl/UserCustomRepositoryImpl.java index 7254c8da..bf10c7e2 100644 --- a/src/main/java/org/prgms/locomocoserver/user/domain/querydsl/UserCustomRepositoryImpl.java +++ b/src/main/java/org/prgms/locomocoserver/user/domain/querydsl/UserCustomRepositoryImpl.java @@ -19,13 +19,14 @@ public class UserCustomRepositoryImpl implements UserCustomRepository { private final JPAQueryFactory queryFactory; @Override - public List findAllById(List userIds) { + public List findAllWithImageByIdIn(List userIds) { QUser user = QUser.user; + QImage image = QImage.image; return queryFactory .selectFrom(user) - .where(user.id.in(userIds) - .and(user.deletedAt.isNull())) + .leftJoin(user.profileImage, image).fetchJoin() + .where(user.id.in(userIds)) .fetch(); } From 8e7bac4ef6ae86470dd18c420b4cfe2116b7e1bc Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 18 Oct 2024 19:49:31 +0900 Subject: [PATCH 20/34] =?UTF-8?q?refactor=20#258=20:=20fetchJoin=20?= =?UTF-8?q?=EC=A0=81=EC=9A=A9=EB=90=9C=20=EB=A0=88=ED=8F=AC=EC=A7=80?= =?UTF-8?q?=ED=86=A0=EB=A6=AC=20=EB=A9=94=EC=84=9C=EB=93=9C=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatRoomService.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java index e4006e9a..7fc070c3 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java @@ -22,6 +22,7 @@ import org.prgms.locomocoserver.chat.exception.ChatException; import org.prgms.locomocoserver.user.domain.User; import org.prgms.locomocoserver.user.domain.UserRepository; +import org.prgms.locomocoserver.user.domain.querydsl.UserCustomRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -39,7 +40,7 @@ public class ChatRoomService { private final ChatRoomRepository chatRoomRepository; private final ChatRoomCustomRepository chatRoomCustomRepository; private final ChatParticipantCustomRepository chatParticipantCustomRepository; - private final UserRepository userRepository; + private final UserCustomRepository userCustomRepository; private final ChatMessageMongoCustomRepository chatMessageMongoCustomRepository; private final StompChatService stompChatService; @@ -94,10 +95,14 @@ public ChatMessageDto saveEnterMessage(ChatEnterRequestDto requestDto) { public List getAllChatRoom(Long userId, String cursor, int pageSize) { if (cursor == null) cursor = LocalDateTime.now().toString(); + log.info("START findByParticipantsId"); List chatRooms = chatRoomCustomRepository.findByParticipantsId(userId, cursor, pageSize); + log.info("END findByParticipantsId"); List chatActivityRequestDaos = createChatActivityRequestDao(userId, chatRooms); + log.info("START findLastMessagesAndUnReadMsgCount"); List lastMessages = chatMessageMongoCustomRepository.findLastMessagesAndUnReadMsgCount(chatActivityRequestDaos); + log.info("END findLastMessagesAndUnreadMsgCount"); Map lastMsgMongoMap = lastMessages.stream() .collect(Collectors.toMap( @@ -106,9 +111,12 @@ public List getAllChatRoom(Long userId, String cursor, int pageSize )); List userIds = createUserIds(lastMessages); - Map userMap = userRepository.findByIdIn(userIds).stream() + log.info("START findByIdIn"); + Map userMap = userCustomRepository.findAllWithImageByIdIn(userIds).stream() .collect(Collectors.toMap(User::getId, user -> user)); + log.info("END findByIdIn"); + log.info("START dto Change"); return chatRooms.stream() .map(chatRoom -> { ChatActivityDao dao = lastMsgMongoMap.get(chatRoom.getId()); From a9135a4ae8f67a74b725103c62a88fb349d7f3ff Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Thu, 24 Oct 2024 23:49:07 +0900 Subject: [PATCH 21/34] =?UTF-8?q?chore=20#258=20:=20=EC=82=AC=EC=9A=A9?= =?UTF-8?q?=ED=95=98=EC=A7=80=20=EC=95=8A=EB=8A=94=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatActivityService.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java index a93fde1a..f52d217d 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java @@ -24,12 +24,4 @@ public void updateLastReadMessage(Long chatRoomId, ChatActivityRequestDto reques .orElseThrow(() -> new ChatException(ChatErrorType.CHAT_PARTICIPANT_NOT_FOUND)); chatParticipant.updateLastReadMessageId(requestDto.lastReadMessageId()); } - - @Transactional(readOnly = true) - public int unReadMessageCount(Long roomId, String lastReadMsgId) { - if (lastReadMsgId == null) { - return 0; - } - return (int) chatMessageMongoRepository.countByChatRoomIdAndIdGreaterThan(roomId.toString(), new ObjectId(lastReadMsgId)); - } } From 44b6ae6426ac9429b62c8f7cafc191b243d66793 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 25 Oct 2024 22:51:36 +0900 Subject: [PATCH 22/34] =?UTF-8?q?refactor=20#258=20:=20chatActivity=20?= =?UTF-8?q?=EA=B4=80=EB=A0=A8=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20MongoDB=20?= =?UTF-8?q?=EC=9D=B4=EC=A0=84=20=EB=B0=8F=20=EB=B3=B5=ED=95=A9=EC=9D=B8?= =?UTF-8?q?=EB=8D=B1=EC=8A=A4=20=EC=84=A4=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/domain/mongo/ChatActivity.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivity.java diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivity.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivity.java new file mode 100644 index 00000000..6ec2efbc --- /dev/null +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivity.java @@ -0,0 +1,40 @@ +package org.prgms.locomocoserver.chat.domain.mongo; + +import lombok.Builder; +import lombok.Getter; +import org.bson.types.ObjectId; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.mapping.Document; + +@Getter +@Document(collection = "chat_activity") +@CompoundIndex(def = "{'userId': 1, 'chatRoomId': 1}", name = "user_chatRoom_idx", unique = true) +public class ChatActivity { + @Id + private String id; + private String userId; + private String chatRoomId; + private ObjectId lastReadMsgId; + private long unReadMsgCnt; + + @Builder + public ChatActivity(String userId, String chatRoomId) { + this.userId = userId; + this.chatRoomId = chatRoomId; + this.lastReadMsgId = null; + this.unReadMsgCnt = 0; + } + + public void updateLastReadMessage(String userId, ObjectId lastReadMsgId) { + if (!this.userId.equals(userId)) { + throw new IllegalArgumentException("Invalid User Id : " + userId); + } + this.lastReadMsgId = lastReadMsgId; + this.unReadMsgCnt = 0; + } + + public void increaseUnreadMsgCnt() { + this.unReadMsgCnt++; + } +} From ff226f457ade2a2aa5bd02a903f7fef6a2e7a410 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 25 Oct 2024 22:53:13 +0900 Subject: [PATCH 23/34] =?UTF-8?q?refactor=20#258=20:=20unReadMsgCnt=20?= =?UTF-8?q?=EB=94=B0=EB=A1=9C=20=EA=B4=80=EB=A6=AC=ED=95=98=EB=8F=84?= =?UTF-8?q?=EB=A1=9D=20=EB=A9=94=EC=84=9C=EB=93=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatActivityService.java | 18 ++++++++++++++---- .../domain/mongo/ChatActivityRepository.java | 11 +++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivityRepository.java diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java index f52d217d..f654275e 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java @@ -3,8 +3,11 @@ import lombok.RequiredArgsConstructor; import org.bson.types.ObjectId; import org.prgms.locomocoserver.chat.domain.ChatParticipant; +import org.prgms.locomocoserver.chat.domain.mongo.ChatActivity; +import org.prgms.locomocoserver.chat.domain.mongo.ChatActivityRepository; import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoRepository; import org.prgms.locomocoserver.chat.domain.querydsl.ChatParticipantCustomRepository; +import org.prgms.locomocoserver.chat.dto.ChatActivityDto; import org.prgms.locomocoserver.chat.dto.request.ChatActivityRequestDto; import org.prgms.locomocoserver.chat.exception.ChatErrorType; import org.prgms.locomocoserver.chat.exception.ChatException; @@ -15,13 +18,20 @@ @RequiredArgsConstructor public class ChatActivityService { - private final ChatParticipantCustomRepository chatParticipantRepository; - private final ChatMessageMongoRepository chatMessageMongoRepository; + private final ChatActivityRepository chatActivityRepository; @Transactional public void updateLastReadMessage(Long chatRoomId, ChatActivityRequestDto requestDto) { - ChatParticipant chatParticipant = chatParticipantRepository.findByUserIdAndChatRoomId(requestDto.userId(), chatRoomId) + ChatActivity chatActivity = chatActivityRepository.findByUserIdAndChatRoomId(requestDto.userId().toString(), String.valueOf(chatRoomId)) .orElseThrow(() -> new ChatException(ChatErrorType.CHAT_PARTICIPANT_NOT_FOUND)); - chatParticipant.updateLastReadMessageId(requestDto.lastReadMessageId()); + chatActivity.updateLastReadMessage(requestDto.userId().toString(), new ObjectId(requestDto.lastReadMessageId())); + } + + @Transactional + public ChatActivityDto increaseLastReadMessage(Long chatRoomId, Long userId) { + ChatActivity chatActivity = chatActivityRepository.findByUserIdAndChatRoomId(String.valueOf(userId), String.valueOf(chatRoomId)) + .orElseThrow(() -> new ChatException(ChatErrorType.CHAT_PARTICIPANT_NOT_FOUND)); + chatActivity.increaseUnreadMsgCnt(); + return ChatActivityDto.of(chatActivity.getChatRoomId(), chatActivity.getUnReadMsgCnt()); } } diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivityRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivityRepository.java new file mode 100644 index 00000000..6f82d6db --- /dev/null +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivityRepository.java @@ -0,0 +1,11 @@ +package org.prgms.locomocoserver.chat.domain.mongo; + +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface ChatActivityRepository extends MongoRepository { + Optional findByUserIdAndChatRoomId(String userId, String chatRoomId); +} From 7f24bbf463b668bf17196f1db2dcc4f666d724bf Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 25 Oct 2024 22:54:58 +0900 Subject: [PATCH 24/34] =?UTF-8?q?feat=20#258=20:=20chatActivityDto=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../locomocoserver/chat/dto/ChatActivityDto.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/java/org/prgms/locomocoserver/chat/dto/ChatActivityDto.java diff --git a/src/main/java/org/prgms/locomocoserver/chat/dto/ChatActivityDto.java b/src/main/java/org/prgms/locomocoserver/chat/dto/ChatActivityDto.java new file mode 100644 index 00000000..d749c762 --- /dev/null +++ b/src/main/java/org/prgms/locomocoserver/chat/dto/ChatActivityDto.java @@ -0,0 +1,14 @@ +package org.prgms.locomocoserver.chat.dto; + +import org.prgms.locomocoserver.chat.domain.mongo.ChatActivity; + +public record ChatActivityDto( + String userId, + String chatRoomId, + String lastReadMsgId, + long unReadMsgCnt +) { + public static ChatActivityDto of(ChatActivity chatActivity) { + return new ChatActivityDto(chatActivity.getUserId(), chatActivity.getChatRoomId(), chatActivity.getLastReadMsgId().toString(), chatActivity.getUnReadMsgCnt()); + } +} From d2f541df413fee49f6e618c1e0051088b7680bfe Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 25 Oct 2024 22:55:25 +0900 Subject: [PATCH 25/34] =?UTF-8?q?feat=20#258=20:=20unReadMsg=20count=20?= =?UTF-8?q?=EC=A6=9D=EA=B0=80=20api=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/presentation/ChatActivityController.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatActivityController.java b/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatActivityController.java index f74fa059..814681a7 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatActivityController.java +++ b/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatActivityController.java @@ -2,7 +2,10 @@ import lombok.RequiredArgsConstructor; import org.prgms.locomocoserver.chat.application.ChatActivityService; +import org.prgms.locomocoserver.chat.dto.ChatActivityDto; import org.prgms.locomocoserver.chat.dto.request.ChatActivityRequestDto; +import org.prgms.locomocoserver.global.annotation.GetUser; +import org.prgms.locomocoserver.user.domain.User; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -19,5 +22,12 @@ public ResponseEntity updateLastReadMessage(@PathVariable Long chatRoomId, chatActivityService.updateLastReadMessage(chatRoomId, request); return ResponseEntity.ok().build(); } + + @PatchMapping("/chats/activity/{chatRoomId}/increase-count") + public ResponseEntity increaseUnReadMsgCnt(@PathVariable Long chatRoomId, + @GetUser User user) { + ChatActivityDto chatActivityDto = chatActivityService.increaseLastReadMessage(chatRoomId, user.getId()); + return ResponseEntity.ok(chatActivityDto); + } } From d33a6f30f030e6410ccbdd22c29bb90a417c435b Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Fri, 25 Oct 2024 22:56:16 +0900 Subject: [PATCH 26/34] =?UTF-8?q?refactor=20#258=20:=20=ED=8C=8C=EB=9D=BC?= =?UTF-8?q?=EB=AF=B8=ED=84=B0=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../locomocoserver/chat/application/ChatActivityService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java index f654275e..700b2942 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java @@ -32,6 +32,6 @@ public ChatActivityDto increaseLastReadMessage(Long chatRoomId, Long userId) { ChatActivity chatActivity = chatActivityRepository.findByUserIdAndChatRoomId(String.valueOf(userId), String.valueOf(chatRoomId)) .orElseThrow(() -> new ChatException(ChatErrorType.CHAT_PARTICIPANT_NOT_FOUND)); chatActivity.increaseUnreadMsgCnt(); - return ChatActivityDto.of(chatActivity.getChatRoomId(), chatActivity.getUnReadMsgCnt()); + return ChatActivityDto.of(chatActivity); } } From a630d875d6f038d39f9d8e00ac446bdaf30bf69f Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Sat, 26 Oct 2024 17:54:48 +0900 Subject: [PATCH 27/34] =?UTF-8?q?chore=20#258=20:=20=EC=82=AC=EC=9A=A9?= =?UTF-8?q?=ED=95=98=EC=A7=80=20=EC=95=8A=EB=8A=94=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatActivityService.java | 11 ----------- .../chat/presentation/ChatActivityController.java | 7 ------- 2 files changed, 18 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java index 700b2942..de7758a1 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatActivityService.java @@ -2,12 +2,8 @@ import lombok.RequiredArgsConstructor; import org.bson.types.ObjectId; -import org.prgms.locomocoserver.chat.domain.ChatParticipant; import org.prgms.locomocoserver.chat.domain.mongo.ChatActivity; import org.prgms.locomocoserver.chat.domain.mongo.ChatActivityRepository; -import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoRepository; -import org.prgms.locomocoserver.chat.domain.querydsl.ChatParticipantCustomRepository; -import org.prgms.locomocoserver.chat.dto.ChatActivityDto; import org.prgms.locomocoserver.chat.dto.request.ChatActivityRequestDto; import org.prgms.locomocoserver.chat.exception.ChatErrorType; import org.prgms.locomocoserver.chat.exception.ChatException; @@ -27,11 +23,4 @@ public void updateLastReadMessage(Long chatRoomId, ChatActivityRequestDto reques chatActivity.updateLastReadMessage(requestDto.userId().toString(), new ObjectId(requestDto.lastReadMessageId())); } - @Transactional - public ChatActivityDto increaseLastReadMessage(Long chatRoomId, Long userId) { - ChatActivity chatActivity = chatActivityRepository.findByUserIdAndChatRoomId(String.valueOf(userId), String.valueOf(chatRoomId)) - .orElseThrow(() -> new ChatException(ChatErrorType.CHAT_PARTICIPANT_NOT_FOUND)); - chatActivity.increaseUnreadMsgCnt(); - return ChatActivityDto.of(chatActivity); - } } diff --git a/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatActivityController.java b/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatActivityController.java index 814681a7..7ff608d3 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatActivityController.java +++ b/src/main/java/org/prgms/locomocoserver/chat/presentation/ChatActivityController.java @@ -22,12 +22,5 @@ public ResponseEntity updateLastReadMessage(@PathVariable Long chatRoomId, chatActivityService.updateLastReadMessage(chatRoomId, request); return ResponseEntity.ok().build(); } - - @PatchMapping("/chats/activity/{chatRoomId}/increase-count") - public ResponseEntity increaseUnReadMsgCnt(@PathVariable Long chatRoomId, - @GetUser User user) { - ChatActivityDto chatActivityDto = chatActivityService.increaseLastReadMessage(chatRoomId, user.getId()); - return ResponseEntity.ok(chatActivityDto); - } } From 67d2612369cfd14b1cfadd4218b8baf317e3093d Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Sat, 26 Oct 2024 17:55:36 +0900 Subject: [PATCH 28/34] =?UTF-8?q?refactor=20#258=20:=20unReadMsgCnt=20?= =?UTF-8?q?=ED=95=84=EB=93=9C=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../locomocoserver/chat/domain/mongo/ChatActivity.java | 7 ------- .../org/prgms/locomocoserver/chat/dto/ChatActivityDto.java | 5 ++--- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivity.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivity.java index 6ec2efbc..c43d749b 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivity.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatActivity.java @@ -16,14 +16,12 @@ public class ChatActivity { private String userId; private String chatRoomId; private ObjectId lastReadMsgId; - private long unReadMsgCnt; @Builder public ChatActivity(String userId, String chatRoomId) { this.userId = userId; this.chatRoomId = chatRoomId; this.lastReadMsgId = null; - this.unReadMsgCnt = 0; } public void updateLastReadMessage(String userId, ObjectId lastReadMsgId) { @@ -31,10 +29,5 @@ public void updateLastReadMessage(String userId, ObjectId lastReadMsgId) { throw new IllegalArgumentException("Invalid User Id : " + userId); } this.lastReadMsgId = lastReadMsgId; - this.unReadMsgCnt = 0; - } - - public void increaseUnreadMsgCnt() { - this.unReadMsgCnt++; } } diff --git a/src/main/java/org/prgms/locomocoserver/chat/dto/ChatActivityDto.java b/src/main/java/org/prgms/locomocoserver/chat/dto/ChatActivityDto.java index d749c762..5924239f 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/dto/ChatActivityDto.java +++ b/src/main/java/org/prgms/locomocoserver/chat/dto/ChatActivityDto.java @@ -5,10 +5,9 @@ public record ChatActivityDto( String userId, String chatRoomId, - String lastReadMsgId, - long unReadMsgCnt + String lastReadMsgId ) { public static ChatActivityDto of(ChatActivity chatActivity) { - return new ChatActivityDto(chatActivity.getUserId(), chatActivity.getChatRoomId(), chatActivity.getLastReadMsgId().toString(), chatActivity.getUnReadMsgCnt()); + return new ChatActivityDto(chatActivity.getUserId(), chatActivity.getChatRoomId(), chatActivity.getLastReadMsgId().toString()); } } From 4dc1276f21e578f53b1cbe4b69b34832e7bee738 Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Sat, 26 Oct 2024 17:58:59 +0900 Subject: [PATCH 29/34] =?UTF-8?q?refactor=20#258=20:=20chatActivity=20?= =?UTF-8?q?=EC=A0=95=EB=B3=B4=20=EC=A0=80=EC=9E=A5=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatRoomService.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java index 7fc070c3..32789d8e 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java @@ -8,6 +8,8 @@ import org.prgms.locomocoserver.chat.domain.ChatParticipant; import org.prgms.locomocoserver.chat.domain.ChatRoom; import org.prgms.locomocoserver.chat.domain.ChatRoomRepository; +import org.prgms.locomocoserver.chat.domain.mongo.ChatActivity; +import org.prgms.locomocoserver.chat.domain.mongo.ChatActivityRepository; import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoCustomRepository; import org.prgms.locomocoserver.chat.domain.querydsl.ChatParticipantCustomRepository; import org.prgms.locomocoserver.chat.domain.querydsl.ChatRoomCustomRepository; @@ -21,7 +23,6 @@ import org.prgms.locomocoserver.chat.exception.ChatErrorType; import org.prgms.locomocoserver.chat.exception.ChatException; import org.prgms.locomocoserver.user.domain.User; -import org.prgms.locomocoserver.user.domain.UserRepository; import org.prgms.locomocoserver.user.domain.querydsl.UserCustomRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -42,6 +43,7 @@ public class ChatRoomService { private final ChatParticipantCustomRepository chatParticipantCustomRepository; private final UserCustomRepository userCustomRepository; private final ChatMessageMongoCustomRepository chatMessageMongoCustomRepository; + private final ChatActivityRepository chatActivityRepository; private final StompChatService stompChatService; private final ChatMessagePolicy chatMessagePolicy; @@ -56,6 +58,9 @@ public void enterChatRoom(ChatEnterRequestDto requestDto) { ChatParticipant chatParticipant = chatParticipantCustomRepository.save(ChatParticipant.builder().user(requestDto.participant()) .chatRoom(chatRoom).build()).orElseThrow(() -> new RuntimeException("채팅방 참여에 실패했습니다.")); + chatActivityRepository.save(ChatActivity.builder().chatRoomId(requestDto.chatRoomId().toString()) + .userId(requestDto.participant().getId().toString()).build()); + chatRoom.addChatParticipant(chatParticipant); stompChatService.sendToSubscribers(chatMessageDto); } @@ -69,6 +74,8 @@ public ChatRoom createChatRoom(ChatCreateRequestDto requestDto) { chatRoom.addChatParticipant(chatParticipant); chatRoomRepository.save(chatRoom); // mysql chat room create + chatActivityRepository.save(ChatActivity.builder() + .chatRoomId(chatRoom.getId().toString()).userId(requestDto.creator().getId().toString()).build()); chatMessagePolicy.saveEnterMessage(chatRoom.getId(), chatParticipant.getUser()); @@ -77,7 +84,9 @@ public ChatRoom createChatRoom(ChatCreateRequestDto requestDto) { @Transactional public ChatMessageDto saveChatMessage(ChatMessageRequestDto requestDto) { - return chatMessagePolicy.saveChatMessage(requestDto.chatRoomId(), requestDto); + ChatMessageDto chatMessageDto = chatMessagePolicy.saveChatMessage(requestDto.chatRoomId(), requestDto); + + return chatMessageDto; } @Transactional From 64df0ae2fb45b9a4319af63c2e5b43a41ae889ab Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Sat, 26 Oct 2024 18:00:27 +0900 Subject: [PATCH 30/34] =?UTF-8?q?chore=20#258=20:=20=EA=B8=B0=EC=A1=B4=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EA=B0=80=EB=8F=85=EC=84=B1=20=ED=96=A5?= =?UTF-8?q?=EC=83=81=20=EC=8B=9C=ED=82=A4=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ChatMessageMongoCustomRepository.java | 67 ++++++++++--------- 1 file changed, 35 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java index 9387c1ae..939f1414 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java @@ -42,22 +42,23 @@ public List findAllChatMessages(Long roomId, String cursorValu public List findLastMessagesAndUnReadMsgCount(List chatRoomInfoDtos) { // 1. 채팅방 roomId 목록 생성 List chatRoomIds = chatRoomInfoDtos.stream() - .map(dao -> dao.chatRoomId().toString()) + .map(ChatActivityRequestDao::chatRoomId) .collect(Collectors.toList()); // 2. 채팅방 필터링 (roomId 기반) - AggregationOperation matchChatRooms = Aggregation.match(Criteria.where("chatRoomId").in(chatRoomIds)); + Criteria criteria = Criteria.where("chatRoomId").in(chatRoomIds); + AggregationOperation matchChatRooms = Aggregation.match(criteria); // 3. 메시지 시간 순으로 정렬 (최신 메시지가 상단에 오도록) AggregationOperation sortMessagesByCreatedAtDesc = Aggregation.sort(Sort.by(Sort.Direction.DESC, "createdAt")); // 4. 각 채팅방별로 마지막 메시지를 그룹화하고 필요한 필드 선택 AggregationOperation groupLastMessage = Aggregation.group("chatRoomId") - .first("chatRoomId").as("chatRoomId") // 채팅방 ID 가져오기 - .first("senderId").as("senderId") // 마지막 메시지 보낸 사람 - .first("message").as("message") // 마지막 메시지 내용 - .first("createdAt").as("createdAt") // 마지막 메시지 시간 - .first("_id").as("chatMessageId"); // 마지막 메시지의 MongoDB _id + .first("chatRoomId").as("chatRoomId") + .first("senderId").as("senderId") + .first("message").as("message") + .first("createdAt").as("createdAt") + .first("_id").as("chatMessageId"); // 5. 필요 필드만 선택하는 project 단계 추가 AggregationOperation projectFields = Aggregation.project() @@ -67,47 +68,49 @@ public List findLastMessagesAndUnReadMsgCount(List aggregationResults = mongoTemplate.aggregate(aggregation, "chat_messages", ChatActivityDao.class); + List lastMessages = mongoTemplate.aggregate(aggregation, "chat_messages", ChatActivityDao.class) + .getMappedResults(); - // 8. 마지막 메시지 결과 반환 - List lastMessages = aggregationResults.getMappedResults(); - - // 9. 읽지 않은 메시지 수 계산을 위한 roomId와 lastReadMsgId 맵 생성 + // 8. 읽지 않은 메시지 수 계산을 위한 roomId와 lastReadMsgId 맵 생성 Map lastReadMessageIdMap = chatRoomInfoDtos.stream() .filter(dao -> dao.lastReadMsgId() != null) .collect(Collectors.toMap( - dao -> dao.chatRoomId().toString(), - dao -> dao.lastReadMsgId() + ChatActivityRequestDao::chatRoomId, + ChatActivityRequestDao::lastReadMsgId )); - // 10. 읽지 않은 메시지 수를 가져오기 위한 쿼리 생성 + // 9. unread 메시지 수를 가져오기 위한 쿼리 생성 List unreadCounts = lastMessages.stream() .map(chatActivityDao -> { - String chatRoomId = chatActivityDao.chatRoomId(); // chatRoomId 가져오기 - ObjectId lastReadMsgId = lastReadMessageIdMap.get(chatRoomId); // lastReadMsgId 가져오기 - - // 11. unread 메시지 수 계산 쿼리 - long unreadCount = mongoTemplate.getCollection("chat_messages").countDocuments(Filters.and( - Filters.eq("chatRoomId", chatRoomId), - Filters.gt("_id", lastReadMsgId) - )); - - // 12. 읽지 않은 메시지 수와 마지막 메시지 결합 - return new ChatActivityDao(String.valueOf(unreadCount), chatActivityDao.chatRoomId(), chatActivityDao.chatMessageId(), chatActivityDao.senderId(), chatActivityDao.message(), chatActivityDao.createdAt()); + String chatRoomId = chatActivityDao.chatRoomId(); + ObjectId lastReadMsgId = lastReadMessageIdMap.getOrDefault(chatRoomId, null); + + // 10. unread 메시지 수 계산 쿼리 + long unreadCount = mongoTemplate.getCollection("chat_messages") + .countDocuments(Filters.and( + Filters.eq("chatRoomId", chatRoomId), + Filters.gt("_id", lastReadMsgId) + )); + + // 11. 읽지 않은 메시지 수와 마지막 메시지 결합 + return new ChatActivityDao(String.valueOf(unreadCount), chatActivityDao.chatRoomId(), + chatActivityDao.chatMessageId(), chatActivityDao.senderId(), + chatActivityDao.message(), chatActivityDao.createdAt()); }) .collect(Collectors.toList()); - // 13. 결과 반환 + // 12. 결과 반환 return unreadCounts; } + } From d6d7f2aab773032507e714b7d63df8b5c525591e Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Sat, 26 Oct 2024 19:11:18 +0900 Subject: [PATCH 31/34] =?UTF-8?q?chore=20#258=20:=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../prgms/locomocoserver/chat/application/ChatRoomService.java | 1 - .../chat/domain/mongo/ChatMessageMongoCustomRepository.java | 1 - 2 files changed, 2 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java index 32789d8e..e2427220 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java @@ -99,7 +99,6 @@ public ChatMessageDto saveEnterMessage(ChatEnterRequestDto requestDto) { return chatMessagePolicy.saveEnterMessage(requestDto.chatRoomId(), requestDto.participant()); } - @Transactional(readOnly = true) public List getAllChatRoom(Long userId, String cursor, int pageSize) { if (cursor == null) cursor = LocalDateTime.now().toString(); diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java index 939f1414..a369a083 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java @@ -112,5 +112,4 @@ public List findLastMessagesAndUnReadMsgCount(List Date: Thu, 31 Oct 2024 01:56:58 +0900 Subject: [PATCH 32/34] =?UTF-8?q?refactor=20#258=20:=20Aggregation=20pipel?= =?UTF-8?q?ine=20=ED=99=9C=EC=9A=A9=ED=95=B4=20=EC=9D=BD=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EC=9D=80=20=EB=A9=94=EC=8B=9C=EC=A7=80=20=EC=88=98=20?= =?UTF-8?q?=EC=A7=91=EA=B3=84=20=EC=BF=BC=EB=A6=AC=20=EC=B5=9C=EC=A0=81?= =?UTF-8?q?=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ChatMessageMongoCustomRepository.java | 126 +++++++++--------- 1 file changed, 66 insertions(+), 60 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java index a369a083..f0654fa2 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java +++ b/src/main/java/org/prgms/locomocoserver/chat/domain/mongo/ChatMessageMongoCustomRepository.java @@ -2,6 +2,7 @@ import com.mongodb.client.model.Filters; import lombok.RequiredArgsConstructor; +import org.bson.Document; import org.bson.types.ObjectId; import org.prgms.locomocoserver.chat.dao.ChatActivityDao; import org.prgms.locomocoserver.chat.dao.ChatActivityRequestDao; @@ -10,6 +11,7 @@ import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationOperation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.convert.MongoConverter; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Repository; @@ -39,77 +41,81 @@ public List findAllChatMessages(Long roomId, String cursorValu } @Transactional(readOnly = true) - public List findLastMessagesAndUnReadMsgCount(List chatRoomInfoDtos) { - // 1. 채팅방 roomId 목록 생성 - List chatRoomIds = chatRoomInfoDtos.stream() - .map(ChatActivityRequestDao::chatRoomId) - .collect(Collectors.toList()); + public List findLastMessagesAndUnReadMsgCount(String userId, List chatRoomIds) { + // 1. 채팅방별 마지막 메시지 조회 + Map lastMsgMap = findLastMessages(chatRoomIds); + + // 2. 채팅방별 lastReadMsgId 조회 + Map lastReadMsgIdMap = fetchLastReadMsgIds(userId, chatRoomIds); + + // 3. 읽지 않은 메시지 수 계산 기준 생성 + List criteriaList = createUnreadMessageCriteria(lastReadMsgIdMap); + + // 4. 읽지 않은 메시지 수 집계 + return countUnreadMessages(criteriaList, lastMsgMap); + } - // 2. 채팅방 필터링 (roomId 기반) - Criteria criteria = Criteria.where("chatRoomId").in(chatRoomIds); - AggregationOperation matchChatRooms = Aggregation.match(criteria); - - // 3. 메시지 시간 순으로 정렬 (최신 메시지가 상단에 오도록) - AggregationOperation sortMessagesByCreatedAtDesc = Aggregation.sort(Sort.by(Sort.Direction.DESC, "createdAt")); - - // 4. 각 채팅방별로 마지막 메시지를 그룹화하고 필요한 필드 선택 - AggregationOperation groupLastMessage = Aggregation.group("chatRoomId") - .first("chatRoomId").as("chatRoomId") - .first("senderId").as("senderId") - .first("message").as("message") - .first("createdAt").as("createdAt") - .first("_id").as("chatMessageId"); - - // 5. 필요 필드만 선택하는 project 단계 추가 - AggregationOperation projectFields = Aggregation.project() - .and("chatRoomId").as("chatRoomId") - .and("senderId").as("senderId") - .and("message").as("message") - .and("createdAt").as("createdAt") - .and("chatMessageId").as("chatMessageId"); - - // 6. Aggregation Pipeline 생성 + // 마지막 메시지 조회 + private Map findLastMessages(List chatRoomIds) { Aggregation aggregation = Aggregation.newAggregation( - matchChatRooms, - sortMessagesByCreatedAtDesc, - groupLastMessage, - projectFields + Aggregation.match(Criteria.where("chatRoomId").in(chatRoomIds)), + Aggregation.sort(Sort.by(Sort.Direction.DESC, "createdAt")), + Aggregation.group("chatRoomId") + .first("chatRoomId").as("chatRoomId") + .first("senderId").as("senderId") + .first("message").as("message") + .first("createdAt").as("createdAt") + .first("_id").as("chatMessageId"), + Aggregation.project("chatRoomId", "senderId", "message", "createdAt", "chatMessageId") ); - // 7. Aggregation 결과 실행 List lastMessages = mongoTemplate.aggregate(aggregation, "chat_messages", ChatActivityDao.class) .getMappedResults(); - // 8. 읽지 않은 메시지 수 계산을 위한 roomId와 lastReadMsgId 맵 생성 - Map lastReadMessageIdMap = chatRoomInfoDtos.stream() - .filter(dao -> dao.lastReadMsgId() != null) + return lastMessages.stream() + .collect(Collectors.toMap(ChatActivityDao::chatRoomId, chatActivityDao -> chatActivityDao)); + } + + // lastReadMsgId 조회 + private Map fetchLastReadMsgIds(String userId, List chatRoomIds) { + Query query = new Query(Criteria.where("userId").is(userId).and("chatRoomId").in(chatRoomIds)); + query.fields().include("chatRoomId").include("lastReadMsgId"); + + List results = mongoTemplate.find(query, Document.class, "chat_activity"); + + return results.stream() + .filter(doc -> doc.getObjectId("lastReadMsgId") != null) .collect(Collectors.toMap( - ChatActivityRequestDao::chatRoomId, - ChatActivityRequestDao::lastReadMsgId + doc -> doc.getString("chatRoomId"), + doc -> doc.getObjectId("lastReadMsgId") )); + } - // 9. unread 메시지 수를 가져오기 위한 쿼리 생성 - List unreadCounts = lastMessages.stream() - .map(chatActivityDao -> { - String chatRoomId = chatActivityDao.chatRoomId(); - ObjectId lastReadMsgId = lastReadMessageIdMap.getOrDefault(chatRoomId, null); - - // 10. unread 메시지 수 계산 쿼리 - long unreadCount = mongoTemplate.getCollection("chat_messages") - .countDocuments(Filters.and( - Filters.eq("chatRoomId", chatRoomId), - Filters.gt("_id", lastReadMsgId) - )); - - // 11. 읽지 않은 메시지 수와 마지막 메시지 결합 - return new ChatActivityDao(String.valueOf(unreadCount), chatActivityDao.chatRoomId(), - chatActivityDao.chatMessageId(), chatActivityDao.senderId(), - chatActivityDao.message(), chatActivityDao.createdAt()); - }) + // 읽지 않은 메시지 수 계산 기준 생성 + private List createUnreadMessageCriteria(Map lastReadMsgIdMap) { + return lastReadMsgIdMap.entrySet().stream() + .map(entry -> Criteria.where("chatRoomId").is(entry.getKey()).and("_id").gt(entry.getValue())) .collect(Collectors.toList()); - - // 12. 결과 반환 - return unreadCounts; } + // 읽지 않은 메시지 수 집계 + private List countUnreadMessages(List criteriaList, Map lastMsgMap) { + Aggregation aggregation = Aggregation.newAggregation( + Aggregation.match(new Criteria().orOperator(criteriaList.toArray(new Criteria[0]))), + Aggregation.group("chatRoomId").count().as("unreadCount"), + Aggregation.project("unreadCount").and("chatRoomId").previousOperation() + ); + + AggregationResults results = mongoTemplate.aggregate(aggregation, "chat_messages", Document.class); + + return results.getMappedResults().stream() + .map(result -> { + String chatRoomId = result.getString("chatRoomId"); + Integer unreadCount = result.getInteger("unreadCount"); + ChatActivityDao chatActivityDao = lastMsgMap.get(chatRoomId); + return new ChatActivityDao(String.valueOf(unreadCount), chatRoomId, chatActivityDao.chatMessageId(), + chatActivityDao.senderId(), chatActivityDao.message(), chatActivityDao.createdAt()); + }) + .collect(Collectors.toList()); + } } From a6faec114d6802102cfeebdc59391358fb95276d Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Thu, 31 Oct 2024 01:57:38 +0900 Subject: [PATCH 33/34] =?UTF-8?q?refactor=20#258=20:=20chatActivity=20?= =?UTF-8?q?=EA=B4=80=EB=A0=A8=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20mongoDB?= =?UTF-8?q?=EB=A1=9C=20=EC=9D=B4=EC=A0=84=ED=95=98=EB=A9=B4=EC=84=9C=20?= =?UTF-8?q?=EB=A9=94=EC=84=9C=EB=93=9C=20=ED=8C=8C=EB=9D=BC=EB=AF=B8?= =?UTF-8?q?=ED=84=B0=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatRoomService.java | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java index e2427220..1b125f2c 100644 --- a/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java +++ b/src/main/java/org/prgms/locomocoserver/chat/application/ChatRoomService.java @@ -2,9 +2,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.bson.types.ObjectId; import org.prgms.locomocoserver.chat.dao.ChatActivityDao; -import org.prgms.locomocoserver.chat.dao.ChatActivityRequestDao; import org.prgms.locomocoserver.chat.domain.ChatParticipant; import org.prgms.locomocoserver.chat.domain.ChatRoom; import org.prgms.locomocoserver.chat.domain.ChatRoomRepository; @@ -107,9 +105,9 @@ public List getAllChatRoom(Long userId, String cursor, int pageSize List chatRooms = chatRoomCustomRepository.findByParticipantsId(userId, cursor, pageSize); log.info("END findByParticipantsId"); - List chatActivityRequestDaos = createChatActivityRequestDao(userId, chatRooms); + List chatRoomIds = createChatRoomIds(chatRooms); log.info("START findLastMessagesAndUnReadMsgCount"); - List lastMessages = chatMessageMongoCustomRepository.findLastMessagesAndUnReadMsgCount(chatActivityRequestDaos); + List lastMessages = chatMessageMongoCustomRepository.findLastMessagesAndUnReadMsgCount(userId.toString(), chatRoomIds); log.info("END findLastMessagesAndUnreadMsgCount"); Map lastMsgMongoMap = lastMessages.stream() @@ -175,17 +173,9 @@ private boolean isParticipantExist(ChatRoom chatRoom, User user) { .anyMatch(chatParticipant -> chatParticipant.getUser().getId().equals(user.getId())); } - private List createChatActivityRequestDao(Long userId, List chatRooms) { + private List createChatRoomIds(List chatRooms) { return chatRooms.stream() - .map(chatRoom -> new ChatActivityRequestDao( - chatRoom.getId().toString(), - chatRoom.getChatParticipants().stream() - .filter(p -> p.getUser().getId().equals(userId)) - .findFirst() - .map(user -> new ObjectId(user.getLastReadMessageId())) - .orElse(null) - )) - .collect(Collectors.toList()); + .map(chatRoom -> chatRoom.getId().toString()).collect(Collectors.toList()); } private List createUserIds(List lastMessages) { From 833da76eb854ea05b7d495f868d6f5ab5aa6dc0c Mon Sep 17 00:00:00 2001 From: eugene <81062608+eugene225@users.noreply.github.com> Date: Thu, 31 Oct 2024 01:58:23 +0900 Subject: [PATCH 34/34] =?UTF-8?q?test=20#258=20:=20=EC=B1=84=ED=8C=85?= =?UTF-8?q?=EB=B0=A9=EC=9D=B4=202=EA=B0=9C=20=EC=9D=B4=EC=83=81=EC=9D=BC?= =?UTF-8?q?=20=EB=95=8C=EC=97=90=EB=8F=84=20=EC=9D=98=EB=8F=84=EC=97=90=20?= =?UTF-8?q?=EB=A7=9E=EA=B2=8C=20=EC=BF=BC=EB=A6=AC=EA=B0=80=20=EB=B0=9C?= =?UTF-8?q?=EC=83=9D=ED=95=98=EB=8A=94=EC=A7=80=20=ED=99=95=EC=9D=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/application/ChatRoomServiceTest.java | 67 +++++++++++++------ 1 file changed, 48 insertions(+), 19 deletions(-) diff --git a/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java b/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java index 7cd83ab7..333e8ab7 100644 --- a/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java +++ b/src/test/java/org/prgms/locomocoserver/chat/application/ChatRoomServiceTest.java @@ -1,20 +1,21 @@ package org.prgms.locomocoserver.chat.application; +import org.bson.types.ObjectId; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.prgms.locomocoserver.chat.domain.*; +import org.prgms.locomocoserver.chat.domain.mongo.ChatActivity; +import org.prgms.locomocoserver.chat.domain.mongo.ChatActivityRepository; import org.prgms.locomocoserver.chat.domain.mongo.ChatMessageMongoRepository; import org.prgms.locomocoserver.chat.dto.ChatMessageDto; import org.prgms.locomocoserver.chat.dto.ChatRoomDto; -import org.prgms.locomocoserver.chat.dto.request.ChatActivityRequestDto; import org.prgms.locomocoserver.chat.dto.request.ChatEnterRequestDto; import org.prgms.locomocoserver.chat.dto.request.ChatMessageRequestDto; import org.prgms.locomocoserver.chat.exception.ChatErrorType; import org.prgms.locomocoserver.chat.exception.ChatException; import org.prgms.locomocoserver.global.TestFactory; import org.prgms.locomocoserver.image.domain.ImageRepository; -import org.prgms.locomocoserver.mogakkos.application.MogakkoParticipationService; import org.prgms.locomocoserver.mogakkos.application.MogakkoService; import org.prgms.locomocoserver.mogakkos.domain.Mogakko; import org.prgms.locomocoserver.mogakkos.domain.MogakkoRepository; @@ -25,7 +26,6 @@ import org.prgms.locomocoserver.mogakkos.domain.vo.AddressInfo; import org.prgms.locomocoserver.mogakkos.dto.LocationInfoDto; import org.prgms.locomocoserver.mogakkos.dto.request.MogakkoCreateRequestDto; -import org.prgms.locomocoserver.mogakkos.dto.request.ParticipationRequestDto; import org.prgms.locomocoserver.mogakkos.dto.response.MogakkoCreateResponseDto; import org.prgms.locomocoserver.user.domain.User; import org.prgms.locomocoserver.user.domain.UserRepository; @@ -34,7 +34,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.DefaultTransactionDefinition; import java.time.LocalDate; @@ -63,6 +62,8 @@ class ChatRoomServiceTest { @Autowired private ChatMessageMongoRepository chatMessageMongoRepository; @Autowired + private ChatActivityRepository chatActivityRepository; + @Autowired private MogakkoRepository mogakkoRepository; @Autowired private ChatParticipantRepository chatParticipantRepository; @@ -85,6 +86,7 @@ void tearDown() { mogakkoRepository.deleteAll(); userRepository.deleteAll(); imageRepository.deleteAll(); + chatActivityRepository.deleteAll(); chatMessageMongoRepository.deleteAll(); } @@ -136,29 +138,56 @@ void success_get_all_chat_rooms_partial_unread_messages() { User user1 = TestFactory.createUser(); imageRepository.saveAll(List.of(user.getProfileImage(), user1.getProfileImage())); userRepository.saveAll(List.of(user, user1)); - Mogakko mogakko = TestFactory.createMogakko(user); - mogakko = mogakkoRepository.save(mogakko); - ChatRoom chatRoom1 = TestFactory.createChatRoom(user, mogakko); + + Mogakko mogakko1 = TestFactory.createMogakko(user); + Mogakko mogakko2 = TestFactory.createMogakko(user1); + mogakkoRepository.saveAll(List.of(mogakko1, mogakko2)); + + ChatRoom chatRoom1 = TestFactory.createChatRoom(user, mogakko1); + ChatRoom chatRoom2 = TestFactory.createChatRoom(user, mogakko2); chatRoom1 = chatRoomRepository.save(chatRoom1); - participantRepository.save(new Participant(null, null, user, mogakko)); - ChatParticipant chatParticipant = chatParticipantRepository.save(new ChatParticipant(user, chatRoom1)); - chatRoom1.addChatParticipant(chatParticipant); + chatRoom2 = chatRoomRepository.save(chatRoom2); + + participantRepository.save(new Participant(null, null, user, mogakko1)); + participantRepository.save(new Participant(null, null, user, mogakko2)); + + ChatParticipant chatParticipant1 = chatParticipantRepository.save(new ChatParticipant(user, chatRoom1)); + ChatParticipant chatParticipant2 = chatParticipantRepository.save(new ChatParticipant(user, chatRoom2)); + chatRoom1.addChatParticipant(chatParticipant1); + chatRoom2.addChatParticipant(chatParticipant2); + + ChatActivity chatActivity1 = chatActivityRepository.save(new ChatActivity(user.getId().toString(), chatRoom1.getId().toString())); + ChatActivity chatActivity2 = chatActivityRepository.save(new ChatActivity(user.getId().toString(), chatRoom2.getId().toString())); ChatMessageDto messageDto1 = mongoChatMessageService.saveChatMessage(chatRoom1.getId(), new ChatMessageRequestDto(chatRoom1.getId(), user.getId(), "test1", null)); ChatMessageDto messageDto2 = mongoChatMessageService.saveChatMessage(chatRoom1.getId(), new ChatMessageRequestDto(chatRoom1.getId(), user.getId(), "test2", null)); + ChatMessageDto messageDto3 = mongoChatMessageService.saveChatMessage(chatRoom2.getId(), new ChatMessageRequestDto(chatRoom2.getId(), user.getId(), "test11", null)); + ChatMessageDto messageDto4 = mongoChatMessageService.saveChatMessage(chatRoom2.getId(), new ChatMessageRequestDto(chatRoom2.getId(), user.getId(), "test22", null)); + ChatMessageDto messageDto5 = mongoChatMessageService.saveChatMessage(chatRoom2.getId(), new ChatMessageRequestDto(chatRoom2.getId(), user.getId(), "test22", null)); + // when - chatParticipant.updateLastReadMessageId(messageDto1.chatMessageId()); - chatParticipantRepository.save(chatParticipant); - System.out.println("-------------" + chatParticipant.getLastReadMessageId()); - List chatRoomDtos = chatRoomService.getAllChatRoom(user.getId(), LocalDateTime.now().toString(), 10); - System.out.println(chatRoomDtos.get(0).updatedAt() + " " + LocalDateTime.now().toString()); + chatParticipant1.updateLastReadMessageId(messageDto1.chatMessageId()); + chatActivity1.updateLastReadMessage(user.getId().toString(), new ObjectId(messageDto1.chatMessageId())); + chatParticipantRepository.save(chatParticipant1); + chatActivityRepository.save(chatActivity1); - for(int i=0; i chatRoomDtos = chatRoomService.getAllChatRoom(user.getId(), LocalDateTime.now().toString(), 10); // then - assertThat(chatRoomDtos.get(0).unReadMsgCnt()).isEqualTo(1); + assertThat(chatRoomDtos.size()).isEqualTo(2); + + for (ChatRoomDto chatRoomDto : chatRoomDtos) { + if (chatRoomDto.roomId().equals(chatRoom1.getId())) { + assertThat(chatRoomDto.unReadMsgCnt()).isEqualTo(1); + } else if (chatRoomDto.roomId().equals(chatRoom2.getId())) { + assertThat(chatRoomDto.unReadMsgCnt()).isEqualTo(2); + } + } } }