Files
mtusi2026lab6/src/main/java/ru/mtusi/messenger/service/ChatService.java
T

136 lines
4.7 KiB
Java

package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.ChatDTO;
import ru.mtusi.messenger.dto.ChatPageDTO;
import ru.mtusi.messenger.dto.CreateChatDTO;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.mapper.ChatMapper;
import ru.mtusi.messenger.model.Chat;
import ru.mtusi.messenger.model.User;
import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.util.CursorCodec;
import ru.mtusi.messenger.validation.ChatValidator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
@Service
@Slf4j
@RequiredArgsConstructor
public class ChatService {
private final ChatMapper chatMapper;
private final ChatValidator chatValidator;
private final ChatRepository chatRepository;
@Transactional
public ChatDTO createChat(UUID caller, CreateChatDTO createChatDTO) {
Set<User> members = chatValidator.validateCreate(caller, createChatDTO);
Chat chat = buildChat(createChatDTO, members);
chat = persistChat(chat);
return chatMapper.toChatDto(chat);
}
private Chat buildChat(CreateChatDTO createChatDTO, Set<User> members) {
Chat chat = chatMapper.toChat(createChatDTO);
chat.setMembers(members);
return chat;
}
private Chat persistChat(Chat chat) {
try {
return chatRepository.saveAndFlush(chat);
} catch (DataIntegrityViolationException e) {
throw new InvalidRequestException("Cannot create chat: invalid data");
}
}
@Transactional(readOnly = true)
public ChatDTO getChatDTO(UUID caller, UUID chatId) {
Chat chat = requireChatForMember(caller, chatId);
return chatMapper.toChatDto(chat);
}
@Transactional(readOnly = true)
public Chat getChat(UUID caller, UUID chatId) {
return requireChatForMember(caller, chatId);
}
private Chat requireChatForMember(UUID caller, UUID chatId) {
Chat chat =
chatRepository
.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
if (chat.getMembers().stream().noneMatch(m -> m.getId().equals(caller))) {
throw new NotFoundException("Chat not found");
}
return chat;
}
@Transactional(readOnly = true)
public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) {
int size = resolveSize(limit);
CursorCodec.Cursor decoded = parseChatsCursor(cursor);
List<Chat> rows = loadChatPage(userId, decoded, size);
return buildPage(rows, size);
}
private int resolveSize(Integer limit) {
return (limit == null) ? 50 : limit;
}
private List<Chat> loadChatPage(UUID userId, CursorCodec.Cursor cursor, int size) {
if (cursor == null) {
return chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1));
}
return chatRepository.findPageByMemberAfterCursor(
userId,
cursor.boundary().createdAt(),
cursor.boundary().id(),
Pageable.ofSize(size + 1));
}
private CursorCodec.Cursor parseChatsCursor(String cursor) {
if (cursor == null) return null;
if (cursor.isEmpty()) throw new InvalidRequestException("Cursor must not be empty");
CursorCodec.Cursor decoded = CursorCodec.decode(cursor);
if (decoded.scopeId() != null) throw new InvalidRequestException("Invalid cursor");
return decoded;
}
private ChatPageDTO buildPage(List<Chat> rows, int size) {
List<ChatDTO> items = rows.stream().limit(size).map(chatMapper::toChatDto).toList();
ChatPageDTO page = new ChatPageDTO();
page.setItems(items);
page.setNextCursor(buildNextCursor(rows, size));
return page;
}
private String buildNextCursor(List<Chat> rows, int size) {
if (rows.size() <= size) {
return null;
}
Chat last = rows.get(size - 1);
return CursorCodec.encode(null, boundaryOf(last));
}
private CursorCodec.PageBoundary boundaryOf(Chat chat) {
return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId());
}
@Transactional
public boolean existsByIdAndMembersId(UUID chatId, UUID userId) {
return chatRepository.existsByIdAndMembersId(chatId, userId);
}
}