forked from mtusi2026/mtusi2026lab2
103 lines
2.6 KiB
Python
103 lines
2.6 KiB
Python
import uuid
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.deps import get_db, get_current_user
|
|
from app.db.models import User as UserModel
|
|
from app.models import CreateMessage, Message as MessageResponse
|
|
from app.services.message_service import (
|
|
MessageService,
|
|
MessageNotFoundError,
|
|
InvalidMessageDataError,
|
|
)
|
|
|
|
|
|
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["Messages"])
|
|
|
|
|
|
def message_to_response(message) -> MessageResponse:
|
|
return MessageResponse(
|
|
id=str(message.id),
|
|
chat_id=str(message.chat_id),
|
|
sender_id=str(message.sender_id),
|
|
text=message.text,
|
|
created_at=message.created_at,
|
|
)
|
|
|
|
|
|
def parse_chat_id(chat_id: str) -> uuid.UUID:
|
|
try:
|
|
return uuid.UUID(chat_id)
|
|
except ValueError:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="Invalid chat UUID",
|
|
) from None
|
|
|
|
|
|
@router.post("", response_model=MessageResponse, status_code=status.HTTP_201_CREATED)
|
|
def create_message(
|
|
chat_id: str,
|
|
body: CreateMessage,
|
|
db: Session = Depends(get_db),
|
|
user: UserModel = Depends(get_current_user),
|
|
):
|
|
parsed_id = parse_chat_id(chat_id)
|
|
|
|
try:
|
|
message = MessageService(db).create_message(
|
|
chat_id=parsed_id,
|
|
sender_id=user.id,
|
|
text=body.text,
|
|
)
|
|
return message_to_response(message)
|
|
|
|
except MessageNotFoundError:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Chat not found",
|
|
) from None
|
|
|
|
except InvalidMessageDataError as exc:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail=str(exc),
|
|
) from None
|
|
|
|
|
|
@router.get("")
|
|
def list_messages(
|
|
chat_id: str,
|
|
limit: int = Query(default=50, ge=1, le=100),
|
|
cursor: str | None = None,
|
|
db: Session = Depends(get_db),
|
|
user: UserModel = Depends(get_current_user),
|
|
):
|
|
parsed_id = parse_chat_id(chat_id)
|
|
|
|
try:
|
|
messages, next_cursor = MessageService(db).get_history(
|
|
chat_id=parsed_id,
|
|
user_id=user.id,
|
|
limit=limit,
|
|
cursor=cursor,
|
|
)
|
|
|
|
return {
|
|
"items": [message_to_response(item) for item in messages],
|
|
"next_cursor": next_cursor,
|
|
}
|
|
|
|
except MessageNotFoundError:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Chat not found",
|
|
) from None
|
|
|
|
except InvalidMessageDataError as exc:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail=str(exc),
|
|
) from None
|