Files
mtusi2026lab4/app/routes/chats.py
T

65 lines
2.0 KiB
Python

from __future__ import annotations
from uuid import UUID
from fastapi import APIRouter, Depends, Query, status
from app.dependencies import get_current_user
from app.schemas import (
ChatPageResponse,
ChatResponse,
CreateChatRequest,
UserResponse,
)
from app.storage import InvalidRequestError, storage
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
def validate_uuid(value: str, field_name: str = "id") -> str:
try:
UUID(value)
return value
except ValueError as exc:
raise InvalidRequestError(f"Поле '{field_name}' не является валидным UUID") from exc
@router.post("", response_model=ChatResponse, status_code=status.HTTP_201_CREATED)
async def create_chat(
body: CreateChatRequest,
current_user: UserResponse = Depends(get_current_user),
) -> ChatResponse:
"""Создание нового чата."""
chat = await storage.create_chat(
caller_id=current_user.id,
title=body.title,
member_ids=body.member_ids,
)
return chat
@router.get("", response_model=ChatPageResponse, status_code=status.HTTP_200_OK)
async def list_chats(
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = Query(default=None),
current_user: UserResponse = Depends(get_current_user),
) -> ChatPageResponse:
"""Список чатов, в которых состоит текущий пользователь."""
items, next_cursor = await storage.list_chats(
caller_id=current_user.id,
limit=limit,
cursor=cursor,
)
return ChatPageResponse(items=items, next_cursor=next_cursor)
@router.get("/{chat_id}", response_model=ChatResponse, status_code=status.HTTP_200_OK)
async def get_chat(
chat_id: str,
current_user: UserResponse = Depends(get_current_user),
) -> ChatResponse:
"""Получение информации о чате по ID."""
valid_id = validate_uuid(chat_id, "chat_id")
chat = await storage.get_chat(caller_id=current_user.id, chat_id=valid_id)
return chat