gpt4 book ai didi

Firebase 聊天 - 删除旧消息

转载 作者:行者123 更新时间:2023-12-03 00:50:00 27 4
gpt4 key购买 nike

我已经创建了一个只有 1 个房间的聊天室、私有(private)消息、审核以及一切,现在一切都很好!当我测试聊天时,我意识到在聊天中输入的所有消息都会被保存,如果有很多人使用聊天,它很快就会占用 Firebase 中的大量空间。

为了向您提供我正在寻找的内容的示例,让我向您展示我如何处理私有(private)消息:

当 John 向 Bob 发送私有(private)消息时,该消息将被添加到 John 和 Bob 的私有(private)消息列表中,如下所示:

/private/John <-- Message appended here
/private/Bob <-- Message appended here

这是 Firebase 在聊天中包含 2 条消息和 2 条私有(private)消息时的外观示例:

{
"chat" : {
"516993ddeea4f" : {
"string" : "Some message here",
"time" : "Sat 13th - 18:20:29",
"username" : "test",
},
"516993e241d1c" : {
"string" : "another message here",
"time" : "Sat 13th - 18:20:34",
"username" : "Test2",
}
},
"private" : {
"test" : {
"516993f1dff57" : {
"string" : "Test PM reply!",
"time" : "Sat 13th - 18:20:49",
"username" : "Test2",
},
"516993eb4ec59" : {
"string" : "Test private message!",
"time" : "Sat 13th - 18:20:43",
"username" : "test",
}
},
"Test2" : {
"516993f26dbe4" : {
"string" : "Test PM reply!",
"time" : "Sat 13th - 18:20:50",
"username" : "Test2",
},
"516993eab8a55" : {
"string" : "Test private message!",
"time" : "Sat 13th - 18:20:42",
"username" : "test",
}
}
}
}

反之亦然。现在,如果鲍勃断开连接,鲍勃的私有(private)消息列表将被删除,但约翰仍然能够看到他与鲍勃的对话,因为他获得了列表上所有消息的副本。如果 John 在 Bob 之后断开连接,Firebase 将被清理并且他们的对话将不再存储。

有没有办法通过常规聊天来实现类似的功能?向所有使用聊天的用户推送消息似乎不是一个好的解决方案(?)。或者是否有可能以某种方式使 Firebase 仅保留最新的 100 条消息?

希望这是有道理的!

亲切的问候

诗。非常感谢 Firebase 团队迄今为止提供的所有帮助,我真的很感激。

最佳答案

有几种不同的方法可以解决这个问题,其中一些方法比其他方法实现起来更复杂。最简单的解决方案是让每个用户只阅读最新的 100 条消息:

var messagesRef = new Firebase("https://<example>.firebaseio.com/message").limit(100);
messagesRef.on("child_added", function(snap) {
// render new chat message.
});
messagesRef.on("child_removed", function(snap) {
// optionally remove this chat message from DOM
// if you only want last 100 messages displayed.
});

您的消息列表仍将包含所有消息,但不会影响性能,因为每个客户端仅询问最后 100 条消息。另外,如果要清理旧数据,最好将每条消息的优先级设置为消息发送时的时间戳。然后,您可以使用以下命令删除所有超过 2 天的消息:

var timestamp = new Date();
timestamp.setDate(timestamp.getDate()-2);
messagesRef.endAt(timestamp).on("child_added", function(snap) {
snap.ref().remove();
});

希望这有帮助!

关于Firebase 聊天 - 删除旧消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15990681/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com