Files
mtusi2026lab2/src/messenger/routers/messages.py
T
2026-10-23 17:24:27 +03:00

47 lines
2.0 KiB
Python

"""Отправка и чтение истории сообщений."""
from __future__ import annotations
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Path, Query, status
from ..access import visible_chat
from ..cursor import KIND_MESSAGES
from ..deps import CursorsDep, CurrentUser, RepositoryDep
from ..models import DEFAULT_LIMIT, MAX_LIMIT, CreateMessage, Message, MessagePage
from ..pagination import build_next_cursor, decoded_cursor
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
@router.post("", status_code=status.HTTP_201_CREATED, summary="Отправить сообщение")
async def create_message(
chat_id: Annotated[UUID, Path()],
payload: CreateMessage,
repository: RepositoryDep,
user: CurrentUser,
) -> Message:
"""Отправитель выводится из идентификации; sender_id в теле не принимается."""
await visible_chat(repository, chat_id, user)
return Message.from_record(await repository.append_message(chat_id, user.id, payload.text))
@router.get("", summary="Сообщения по (created_at, id) по возрастанию")
async def list_messages(
chat_id: Annotated[UUID, Path()],
repository: RepositoryDep,
cursors: CursorsDep,
user: CurrentUser,
limit: Annotated[int, Query(ge=1, le=MAX_LIMIT)] = DEFAULT_LIMIT,
cursor: Annotated[str | None, Query(min_length=1)] = None,
) -> MessagePage:
"""Keyset-пагинация: страница читается по индексу, предыдущие не повторяются."""
await visible_chat(repository, chat_id, user)
scope = str(chat_id)
after = decoded_cursor(cursors, cursor, kind=KIND_MESSAGES, scope=scope)
records, has_more = await repository.list_messages(chat_id, after, limit)
return MessagePage.from_records(
records, build_next_cursor(cursors, KIND_MESSAGES, scope, records, has_more)
)