在 Firebase 聊天中管理未读消息 [英] Managing unread messages in firebase chat

查看:30
本文介绍了在 Firebase 聊天中管理未读消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建实时聊天,与 Skype 非常相似.我在客户端使用 firebase 作为后端和 angularfire.基本上,所有事情看起来都很清楚,但我坚持一件事 - 显示未读消息数.

I'm building real time chat, very similar with skype one. I use firebase as backend and angularfire on client side. Basically, all things are look clear, but I've stuck with one thing - showing of unread messages count.

应用使用非常简单的 Firebase 设计:2 个或更多用户可以在一个房间"中聊天 - 具有唯一名称的根集合.除文本外的聊天消息可以包含元数据" - 发件人 ID、时间戳等.

App uses very simple Firebase design: 2 or more users can chat in a "room" - root collection with unique name. Chat message except of text can contain "metadata" - sender id, timestamp, etc.

简单地说,我需要模拟这个伪代码:

Simply, I need an emulation of this pseudo-code:

room.messages.where({ unread: true }).count()

目前,根据this,(我可以计算某个地点的孩子数吗?没有检索实际的子数据?)和 this 我正在尝试按事务管理每个房间的未读消息计数,并在查看时重置计数.但这是非常棘手的部分,我很好奇,我们这里有什么推荐的方法,可以减少工作量吗?

For now, according to this, (Can I count the children at a location without retrieving the actual child data?) and this I'm trying to manage unread messages count per room by transactions and reset count when viewed. But it is very tricky part, and I'm curious, do we have any recommended approach here, which can reduce amount of job?

推荐答案

您似乎已经回答了很多问题.Firebase 中没有 WHERE 子句,解决方案是使用 snap.numChildren() 作为 FAQ 状态,或者使用计数器作为第二个链接状态.

It seems like you've pretty much answered it. There is no WHERE clause in Firebase, and the solution is to use snap.numChildren() as the FAQ states, or to use a counter, as the second link states.

如果您无论如何要获取聊天消息,或者是一对一聊天,其中总有效负载为 100 KB 或更少(大约 20 条 10kb 消息),那么只需使用 numChildren.如果消息负载相当大,则设置计数器.

If you are going to fetch the chat messages anyway, or it's a one-on-one chat where the total payload would be a hundred kilobytes or less (twenty or so 10kb messages), then just use numChildren. If the message payload is going to be rather large, then set up the counters.

所以你会保持一个计数器:

So you would maintain a counter of:

  • 您的用户阅读了多少消息
  • 存在多少条消息
  • 区别在于未读消息的数量

由于您的消息存在"计数器将被多个用户同时更新,您将使用事务来完成此操作,而不会发生冲突:

Since your "messages exist" counter would be updated by multiple users concurrently, you'd use a transaction to accomplish this without conflicts:

new Firebase(URL_TO_COUNTER).transaction(function(currValue) {
    return (currValue||0)+1;
}, function(err, success, snap) {
    if( err ) { throw err; }
    console.log('counter updated to '+snap.val());
});

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

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