在 Firebase 中管理聊天频道的最佳方式 [英] Best way to manage Chat channels in Firebase

查看:26
本文介绍了在 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.

我在想,如果使用 id 是最好的方法并控制对像 USERID1-USERID2 这样的频道的访问.

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

当然,用户 2 也可以打开同一个频道,所以我想找一些更容易控制的东西.

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

如果你想帮助我,请给我一个使用 firebase url/array 的 javascript 示例.

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

谢谢!

推荐答案

处理这种 1:1 聊天室的常用方法是根据用户 ID 生成聊天室 URL.正如您已经提到的,问题在于任一用户都可以发起聊天,而且在这两种情况下,他们都应该在同一个房间里结束.

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.

您可以通过在复合键中按字典顺序对用户 ID 进行排序来解决此问题.例如使用用户名,而不是 id:

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"; // UID of user 1
var user2 = "Eusthace"; // UID of user 2

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>

一个常见的后续问题似乎是如何显示当前用户的聊天室列表.上面的代码没有解决这个问题.正如在 NoSQL 数据库中常见的那样,您需要扩充数据模型以支持此用例.如果您想显示当前用户的聊天室列表,您应该对数据进行建模以允许这样做.最简单的方法是将每个用户的聊天室列表添加到数据模型中:

A common follow-up questions seems to be how to show a list of chat rooms for the current user. The above code does not address that. As is common in NoSQL databases, you need to augment your data model to allow this use-case. If you want to show a list of chat rooms for the current user, you should model your data to allow that. The easiest way to do this is to add a list of chat rooms for each user to the data model:

"userChatrooms" : {
  "Frank" : {
    "Eusthace_Frank": true
  },
  "Eusthace" : {
    "Eusthace_Frank": true
  }
}

如果您担心键的长度,您可以考虑使用组合 UID 的哈希码而不是完整 UID.

If you're worried about the length of the keys, you can consider using a hash codes of the combined UIDs instead of the full UIDs.

这篇关于在 Firebase 中管理聊天频道的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆