Eusthace Eusthace -4 years ago 71
Javascript Question

Best way to manage Chat channels in Firebase

In my main page I have a list of users and i'd like to choose and open a channel to chat with one of them.

I am thinking if use the id is the best way and control an access of a channel like USERID1-USERID2.

But of course, user 2 can open the same channel too, so I'd like to find something more easy to control.

Please, if you want to help me, give me an example in javascript using a firebase url/array.

Thank you!

Answer Source

A common way to handle such 1:1 chat rooms is to generate the room URL based on the user ids. As you already mention, a problem with this is that either user can initiate the chat and in both cases they should end up in the same room.

You can solve this by ordering the user ids lexicographically in the compound key. For example with user names, instead of ids:

var user1 = "Frank";
var user2 = "Eusthace";

var roomName = 'chat_'+(user1<user2 ? user1+'_'+user2 : user2+'_'+user1);

console.log(user1+', '+user2+' => '+ roomName);
            
user1 = "Eusthace";
user2 = "Frank";

var roomName = 'chat_'+(user1<user2 ? user1+'_'+user2 : user2+'_'+user1);

console.log(user1+', '+user2+' => '+ roomName);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download