vesii
vesii

Reputation: 3128

How to support new messages in a chat room using Firebase cloud database?

I have a question on database modeling. I'm using Firebase Cloud database for my Android app and I have a collection called chatRooms. Each document in that collection contains the following fields:

  1. Chat room name.
  2. Chat room image.
  3. Last message that was sent in the chat room (triggered by firebase functions once new document is created in messages).
  4. Timestamp of last message (also created by firebase functions).
  5. Users - list of users paths in the database (to their documents) that are in that chat room.

Each document also points to another collection messages and each document there contains:

  1. Message.
  2. The name of the message sender.
  3. The path the sender document in the database.
  4. Timestamp of the message.

I would like to add support ot "seen" option, meaning I want to know if I have new messages in a chat room. If I enter to the screen of all of my chat rooms, I want to know if there is a chat room that I haven't seen and then I could "bold" the chat room (or do other stuff to indicate that the user has new messages in that chat room). At first I thought to create an array in the chatRooms level that will contain all of the users that saw the latest message. But I think it could lead to race conditions because it takes time to the firebase functions to run. What would be the best way to support "new messages" in the database? I would like to hear an database modeling suggestion (for example, which field to keep and where to treat it).

Upvotes: 0

Views: 237

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598886

The simplest way to do this is to track the timestamp of the most recent message that each user has seen in each chatroom. You'd do this in the client-side code, when either when loading the data for the chat room, or when a message is shown on screen, with something like if (msg.timestamp > user["last_seen."+room_id]) userDocRef.update("last_seen."+room_id, msg.timestamp).

Then to determine which chatrooms have new messages, you compare the last updated timestamp for that chat room with the last seem timestamp for that user for the chat room.

I'd store these values in the user's document as a map: $chatroomid: timestamp. That way the data will automatically get cleaned up when the user document is removed, it has access control in line with the rest of the user's document, and it seems unlikely you'll want to query the individual room timestamps for a user or that those will grow beyond the 1MB size limit of a document.

Upvotes: 2

Related Questions