cbh-test / cbh /api /message /db_requests.py
brestok's picture
Fix incorrect ObjectId conversion in chat message query
6d1b817
import asyncio
from fastapi import HTTPException
from bson import ObjectId
from cbh.api.chat.model import ChatModel
from cbh.api.message.model import MessageModel
from cbh.api.message.schemas import CreateMessageRequest
from cbh.core.config import settings
async def get_all_chat_messages_obj(chat_id: str) -> tuple[list[MessageModel], ChatModel]:
messages, chat = await asyncio.gather(
settings.DB_CLIENT.messages.find({"chatId": chat_id}).to_list(length=None),
settings.DB_CLIENT.chats.find_one({"_id": ObjectId(chat_id)})
)
messages = [MessageModel.from_mongo(message) for message in messages]
if not chat:
raise HTTPException(status_code=404, detail="Chat not found")
return messages, ChatModel.from_mongo(chat)
async def create_message_obj(chat_id: str, message: CreateMessageRequest) -> MessageModel:
chat = await settings.DB_CLIENT.chats.find_one({"_id": ObjectId(chat_id)})
if not chat:
raise HTTPException(status_code=404, detail="Chat not found")
message = MessageModel(chatId=chat_id,
author=message.author,
text=message.text,
moduleResponse=message.moduleResponse)
await settings.DB_CLIENT.messages.insert_one(message.to_mongo())
return message