Chat is not saved while using scoket.io in fastapi with mongodb (Chat App)

21 Views Asked by At

Chat is not saved while using scoket.io in fastapi using mongoDB

**sometime messages saved but sometimes they are not and i think issue is "concurrency issue"

when i debug this new message appeaar but did nnot save in my db i also use multiple technics but still not able to fix this**

@sio.event
async def message(sid, data):
    """Send message event"""
    print(f"====data date : {datetime.utcnow()}  ==")
    try:
        if data['room_id'] is None:
            raise ValueError(f"Field 'room_id' must be a string, not {data['room_id']}")

        data['message']['sent'] = True
        if "createdAt" in data['message']:
            data['message']["createdAt"] = str(datetime.utcnow()) 
        else:
            data['message']["createdAt"] = str(datetime.utcnow()) 

        await sio.emit('message', data['message'], room=data['room_id'])
        await ConversationService().saveConversations(data['room_id'], data['message'])
    except Exception as e:
        print("Error:", e)

 async def saveConversations(self, room_id, data):
        """" create chat room """
        # room create for chat
        import time
        try:
            chat_room = await Rooms.get_by_user_room_id(room_id)
            mood = False
            if chat_room:
                if chat_room.mood =="Discreet":
                    mood =True
            if "image" in data:
                upload_images = await self.uploadImagesToS3Bucket(
                    room_id.replace("/","-"), data["image"], mood)
                data["image"] = upload_images
                await UserActivitiesService().average_photos_sent(data["user"]["_id"])

            if "audio" in data:
                upload_audio = await self.uploadAudioToS3Bucket(
                    room_id.replace("/","-"), data["audio"])
                data["audio"] = upload_audio

            chat_conversation = await Conversations.get_by_user_room_id(str(room_id))
            
            if chat_conversation is None:
                create_conversation =  Conversations(
                    room_id=str(room_id),
                    messages=[data]
                    )
                await create_conversation.create()
            
            else:
                chat_conversation.messages.append(data)

                await chat_conversation.save()
            return True
        except Exception as e:
            print("error==>>>>>>>>>>>>>>>>>>>>>>>",e)
0

There are 0 best solutions below