forked from mtusi2026/mtusi2026lab4
47 lines
2.1 KiB
Python
47 lines
2.1 KiB
Python
from uuid import UUID
|
|
|
|
from config import LOGGER
|
|
from domain import ChatPageSchema, ChatSchema, CreateChatSchema, UserSchema
|
|
from domain.errors import InvalidRequestError, NotFoundError
|
|
from infrastructure.utils import build_page, decode_cursor
|
|
from interfaces import ChatRepository
|
|
|
|
|
|
class ChatService:
|
|
def __init__(self, chat_repository: ChatRepository) -> None:
|
|
self._chats = chat_repository
|
|
|
|
async def create_chat(
|
|
self, current_user: UserSchema, data: CreateChatSchema
|
|
) -> ChatSchema:
|
|
"""
|
|
Чат создаётся из явного списка существующих участников, включая создателя.
|
|
Существование участников проверяет FK в транзакции создания: отдельная
|
|
предварительная проверка была бы гонкой и не нужна для отката.
|
|
"""
|
|
if current_user.id not in data.member_ids:
|
|
raise InvalidRequestError(
|
|
"member_ids должен содержать текущего пользователя"
|
|
)
|
|
chat = await self._chats.create(data.title, current_user.id, data.member_ids)
|
|
LOGGER.info(
|
|
f"Создан чат {chat.id} пользователем {current_user.id}, "
|
|
f"участников: {len(chat.member_ids)}"
|
|
)
|
|
return chat
|
|
|
|
async def get_chat(self, current_user: UserSchema, chat_id: UUID) -> ChatSchema:
|
|
chat = await self._chats.get_for_member(chat_id, current_user.id)
|
|
if chat is None:
|
|
raise NotFoundError()
|
|
return chat
|
|
|
|
async def list_chats(
|
|
self, current_user: UserSchema, limit: int, cursor: str | None
|
|
) -> ChatPageSchema:
|
|
scope = f"chats:{current_user.id}"
|
|
after = decode_cursor(cursor, scope)
|
|
fetched = await self._chats.list_for_member(current_user.id, after, limit + 1)
|
|
items, next_cursor = build_page(fetched, limit, scope)
|
|
return ChatPageSchema(items=items, next_cursor=next_cursor)
|