feat: port lab3 backend foundation to lab4
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
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 Chat as ChatResponse, CreateChat
|
||||
from app.services.chat_service import (
|
||||
ChatService,
|
||||
ChatNotFoundError,
|
||||
InvalidChatDataError,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["Chats"])
|
||||
|
||||
|
||||
def chat_to_response(chat) -> ChatResponse:
|
||||
return ChatResponse(
|
||||
id=str(chat.id),
|
||||
title=chat.title,
|
||||
member_ids=[str(member.user_id) for member in chat.members],
|
||||
created_at=chat.created_at,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=ChatResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_chat(
|
||||
body: CreateChat,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
try:
|
||||
chat = ChatService(db).create_chat(
|
||||
title=body.title,
|
||||
member_ids=body.member_ids,
|
||||
creator_id=user.id,
|
||||
)
|
||||
return chat_to_response(chat)
|
||||
|
||||
except InvalidChatDataError as exc:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=str(exc),
|
||||
) from None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_chats(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
if cursor is not None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Chat cursor pagination is not implemented yet",
|
||||
)
|
||||
|
||||
chats = ChatService(db).list_chats(user.id)
|
||||
chats = chats[:limit]
|
||||
|
||||
return {
|
||||
"items": [chat_to_response(chat) for chat in chats],
|
||||
"next_cursor": None,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{chat_id}", response_model=ChatResponse)
|
||||
def get_chat(
|
||||
chat_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
try:
|
||||
parsed_id = uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid chat UUID") from None
|
||||
|
||||
try:
|
||||
chat = ChatService(db).get_chat(parsed_id, user.id)
|
||||
return chat_to_response(chat)
|
||||
|
||||
except ChatNotFoundError:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Chat not found",
|
||||
) from None
|
||||
Reference in New Issue
Block a user