Build the chat list with batch queries instead of five queries per chat
Interlocutors, posts, last messages (one subquery by max id) and unread counts (one GROUP BY) are loaded per list. The last message is now picked by id: createdAt is written in the sender's time zone and is not monotonic between users in different zones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -45,7 +45,6 @@ class ChatServiceTest {
|
||||
userRepository, postRepository);
|
||||
|
||||
when(userRepository.existsById(anyLong())).thenReturn(true);
|
||||
when(messageRepository.findFirstByChatIdOrderByCreatedAtDesc(any())).thenReturn(Optional.empty());
|
||||
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
|
||||
when(chatRepository.save(any(Chat.class))).thenAnswer(inv -> {
|
||||
Chat chat = inv.getArgument(0);
|
||||
@@ -112,4 +111,38 @@ class ChatServiceTest {
|
||||
.isInstanceOf(ApiException.class)
|
||||
.hasMessageContaining("самим собой");
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatListIsBuiltWithBatchQueries() {
|
||||
Chat first = new Chat();
|
||||
first.setId(1L);
|
||||
first.setUserOneId(14L);
|
||||
first.setUserTwoId(19L);
|
||||
Chat second = new Chat();
|
||||
second.setId(2L);
|
||||
second.setUserOneId(14L);
|
||||
second.setUserTwoId(20L);
|
||||
when(chatRepository.findAllByUserId(14L)).thenReturn(List.of(first, second));
|
||||
User bob = new User();
|
||||
bob.setId(19L);
|
||||
bob.setName("Боб");
|
||||
bob.setLastName("Иванов");
|
||||
when(userRepository.findAllById(any())).thenReturn(List.of(bob));
|
||||
Message last = new Message();
|
||||
last.setChatId(2L);
|
||||
last.setContent("последнее");
|
||||
last.setCreatedAt(java.time.LocalDateTime.now());
|
||||
when(messageRepository.findLastMessages(any())).thenReturn(List.of(last));
|
||||
when(messageRepository.countUnreadByChat(any(), org.mockito.ArgumentMatchers.eq(14L)))
|
||||
.thenReturn(List.<Object[]>of(new Object[] {2L, 3L}));
|
||||
|
||||
List<ChatDto> chats = chatService.getUserChats(14L);
|
||||
|
||||
// Чат со свежим сообщением — первым
|
||||
assertThat(chats).extracting(ChatDto::getId).containsExactly(2L, 1L);
|
||||
assertThat(chats.get(0).getLastMessage()).isEqualTo("последнее");
|
||||
assertThat(chats.get(0).getUnreadCount()).isEqualTo(3L);
|
||||
assertThat(chats.get(1).getOtherUserName()).isEqualTo("Боб Иванов");
|
||||
org.mockito.Mockito.verify(userRepository, org.mockito.Mockito.times(1)).findAllById(any());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user