backend_and_cms/backend/app/api/routes/messages.py

51 lines
1.4 KiB
Python
Raw Normal View History

2024-09-17 12:11:39 +08:00
import uuid
from typing import Any
from fastapi import APIRouter, HTTPException
from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep
from app.models import MessageCreate, MessagePublic, MessagesPublic, Message
router = APIRouter()
@router.post("/", response_model=Message)
def create_message(*, session: SessionDep, Message_in: MessageCreate) -> Any:
"""
Create new message.
"""
message = Message.model_validate(Message_in)
session.add(message)
session.commit()
session.refresh(message)
return message
@router.get("/", response_model=MessagesPublic)
def read_messages(
session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
) -> Any:
count_statement = select(func.count()).select_from(Message)
count = session.exec(count_statement).one()
statement = select(Message).offset(skip).limit(limit)
messages = session.exec(statement).all()
return MessagesPublic(data=messages, count=count)
@router.delete("/{id}")
def delete_item(
session: SessionDep, current_user: CurrentUser, id: uuid.UUID
) -> Message:
"""
Delete an item.
"""
message = session.get(Message, id)
if not message:
raise HTTPException(status_code=404, detail="Message not found")
session.delete(message)
session.commit()
return Message(message="Message deleted successfully")