forked from mtusi2026/mtusi2026lab4
64 lines
2.0 KiB
Python
64 lines
2.0 KiB
Python
from typing import Annotated
|
|
from uuid import UUID
|
|
|
|
from fastapi import APIRouter, Body, Depends, Header, Query, status
|
|
|
|
from application.api.dependencies import get_current_user
|
|
from domain import (
|
|
IDEMPOTENCY_KEY_MAX_LENGTH,
|
|
IDEMPOTENCY_KEY_PATTERN,
|
|
CreateMessageSchema,
|
|
MessagePageSchema,
|
|
MessageSchema,
|
|
UserSchema,
|
|
)
|
|
from infrastructure.dependencies import ServiceCreator
|
|
from infrastructure.services import MessageService
|
|
|
|
messages_router = APIRouter(
|
|
prefix="/chats/{chat_id}/messages", tags=["Messages"]
|
|
)
|
|
|
|
|
|
@messages_router.post(
|
|
"",
|
|
status_code=status.HTTP_201_CREATED,
|
|
response_model=MessageSchema,
|
|
)
|
|
async def send_message(
|
|
chat_id: UUID,
|
|
body: Annotated[CreateMessageSchema, Body(...)],
|
|
idempotency_key: Annotated[
|
|
str,
|
|
Header(
|
|
alias="Idempotency-Key",
|
|
min_length=1,
|
|
max_length=IDEMPOTENCY_KEY_MAX_LENGTH,
|
|
pattern=IDEMPOTENCY_KEY_PATTERN,
|
|
),
|
|
],
|
|
current_user: UserSchema = Depends(get_current_user),
|
|
service: MessageService = Depends(ServiceCreator.get_message_service),
|
|
) -> MessageSchema:
|
|
"""
|
|
Idempotency-Key обязателен: повтор того же тела возвращает тот же 201
|
|
и то же сообщение, другое тело с тем же ключом — 409. Нет/неверный ключ — 400.
|
|
"""
|
|
return await service.send_message(current_user, chat_id, body, idempotency_key)
|
|
|
|
|
|
@messages_router.get(
|
|
"",
|
|
status_code=status.HTTP_200_OK,
|
|
response_model=MessagePageSchema,
|
|
)
|
|
async def list_messages(
|
|
chat_id: UUID,
|
|
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
|
cursor: Annotated[str | None, Query(min_length=1)] = None,
|
|
current_user: UserSchema = Depends(get_current_user),
|
|
service: MessageService = Depends(ServiceCreator.get_message_service),
|
|
) -> MessagePageSchema:
|
|
"""История чата: keyset cursor по (created_at, id) по возрастанию"""
|
|
return await service.list_messages(current_user, chat_id, limit, cursor)
|