Private chat app which saves contacts/message history with MongoDB Nodejs Socket.io and Redux

Viewed 163

I'm quite new with sockets so I came here to ask for some good practice ideas. To understand better what I want to achieve here is my idea: I made a product creation page in react which has a seller and an option "Send message to the seller". After a buyer clicks to this button I want to make a private chat between the two user.

I want to save this socket connection and all of the messages between the users for both of them in my MongoDB database. So whenever a user simply leaves the site all of the recieved contacts/messages are saved and when he rejoins can continue the chat with the pre-loaded chat history.

So I thought about creating a messages collection and store socket details in document like this:

_id:ObjectId("123")
productId:1
sender:id1
reciever:id2
messages=[{1:"Hey},
          {2:"Nice to meet you"} ...]

And here comes the redux part: When a user is logging in, I want to fetch all of the previous contacts and messages so he can continue chatting with them. But it would be time waisting to fetch the message history every single time, so I thought about using a redux store to get the contacts and history from database and store there. Like this

recievedmessages=[{_id:ObjectId("123") 
                 productId:1
                 sender:id1 
                  reciever:id2
                  messages=[{1:"Hey},{2:"Nice to meet you"} ...]},
                 {othermessage1 ...},
                 {othermessage2 ...},
                 ]
sentMessages=[{sentmessag1, sentmessage2, sentmessage3}]

And when a buyer sends a new message to that user I update my redux store for the buyer, when the seller recives the message from the socket update for him too and lastly my chat history in my mongodb messages field for that specific document. --> I am not sure at this part to have to manage it

Is this a good practice or how should I make this to be effiecent and store data? Thanks in advance.

0 Answers
Related