ЛР 3: масштабирование и отказоустойчивость API
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.example.mtusi_messenger.dto.CreateChatRequest;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import com.example.mtusi_messenger.model.Chat;
|
||||
import com.example.mtusi_messenger.repository.ChatRepository;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
public class ChatService {
|
||||
private final ChatRepository chats; private final UserService users; private final CursorService cursors;
|
||||
public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; }
|
||||
public Chat create(CreateChatRequest r, UUID caller) {
|
||||
Set<UUID> ids = new LinkedHashSet<>(r.member_ids());
|
||||
if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids");
|
||||
for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids");
|
||||
return chats.save(new Chat(UUID.randomUUID(), r.title(), List.copyOf(ids),
|
||||
Instant.now().truncatedTo(ChronoUnit.MICROS)));
|
||||
}
|
||||
public Chat getAccessible(UUID chatId, UUID userId) {
|
||||
users.get(userId);
|
||||
if (!chats.isMember(chatId, userId)) throw ApiExceptions.notFound("Chat not found");
|
||||
return chats.findById(chatId).orElseThrow(() -> ApiExceptions.notFound("Chat not found"));
|
||||
}
|
||||
public List<Chat> page(UUID userId, int limit, String cursor) {
|
||||
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "chats", userId);
|
||||
return chats.findPageForUser(userId, c == null ? null : c.id(), c == null ? null : c.createdAt(), limit + 1);
|
||||
}
|
||||
public String nextCursor(UUID userId,
|
||||
Chat last,
|
||||
boolean hasNext
|
||||
) {
|
||||
return hasNext ? cursors.encode("chats", userId, last.createdAt(), last.id()) : null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user