2

I am building an app using Firebase. One of the features of this app is a chat feature where users can message other users - nothing fancy, just text-based one user to one user messaging. All of the tutorials online that describe how to implement this such as this one or this one utilize anonymous authentication, so many of the principles don't seem to apply. I am having users authenticate before they can use this feature.

It appears that the two main things I have at my disposal are the ability to modify the contents of specific paths (add, edit, delete, change order) in my app's JSON database structure and observe these changes on the client side as they happen. I could easily put every message in the same child and listen for any changes to the message child then parse every message into conversations on the client-side by looking for messages associated with the current user ID. However, this method seems inefficient as it seems to me like I would have to filter out a lot of superfluous messages.

A description of the general flow of how the observation structure should work, what I need to contain in each message, and how to sort into separate conversations efficiently would be very helpful.

Alex Wulff
  • 2,039
  • 3
  • 18
  • 29

1 Answers1

2

Most chat apps work with the concept of chat rooms, either 1:1 rooms for direct conversation, or named rooms between groups of users.

You model each room as a node in your database, with (just) the messages of that room under the room id:

chatrooms
  roomdid1:
    msg1: { from: ..., text: ..., timestamp: ... }
    msg2: { from: ..., text: ..., timestamp: ... }
    msg3: { from: ..., text: ..., timestamp: ... }
  roomdid2:
    msg4: { from: ..., text: ..., timestamp: ... }
    msg5: { from: ..., text: ..., timestamp: ... }
    msg6: { from: ..., text: ..., timestamp: ... }

To load messages for a room, you just listen to that room , e.g. /chatrooms/roomid1.

For an idea on a naming convention for rooms based on the users in them, see http://stackoverflow.com/questions/33540479/best-way-to-manage-chat-channels-in-firebase.

Praveena
  • 6,340
  • 2
  • 40
  • 53
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks for the guidance, this is very helpful. My only thought is that it might get very slow to manually parse through all the chat rooms and see if a user is in one based on the chatroom ID (when they start filling up with data it could get slow to download them all). Would it be good practice to create another node that just contains chatroom ids and search through that instead? – Alex Wulff Dec 23 '17 at 04:50
  • That would indeed be a bad idea. You'd typically get a list of rooms for each user by theur UID. So: `/userrooms/$uid/roomid1: true`, `/userrooms/$uid/roomid2: true`, etc – Frank van Puffelen Dec 23 '17 at 05:12