Firebase聊天 - 删除旧邮件

MrE*_*MrE 12 firebase

我现在只用一个房间,私人消息,节制和一切创建聊天,一切都很棒!在我测试聊天时,我意识到聊天中所有输入的消息都已保存,如果有很多人使用聊天,那么很快就会占用Firebase中相当大的空间.

为了举例说明我正在寻找的内容,让我向您展示我如何处理私人消息:

当John向Bob发送私人消息时,该消息将被添加到John和Bobs私人消息列表中,如下所示:

/private/John <-- Message appended here
/private/Bob <-- Message appended here
Run Code Online (Sandbox Code Playgroud)

这是一个示例,说明firebase在聊天中如何显示2条消息,以及2条私信:

{
  "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",
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

反过来也是如此.现在,如果Bob断开连接,Bobs私人消息列表将被删除,但John仍然可以看到他与Bob的对话,因为他得到了他列表中所有消息的副本.如果John在Bob之后断开连接,Firebase将被清除并且他们的对话不再存储.

有没有办法通过常规聊天实现这样的事情?向正在使用聊天的所有用户发送消息似乎不是一个好的解决方案(?).或者是否可以以某种方式使Firebase仅保留最新的100条消息?

我希望它有意义!

亲切的问候

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

Ana*_*ant 19

有几种不同的方法可以解决这个问题,实施起来比其他方法更复杂.最简单的解决方案是让每个用户只读取最新的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.
});
Run Code Online (Sandbox Code Playgroud)

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

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

希望这可以帮助!

  • 这是可能的,但需要多个步骤.首先,您需要检索具有优先级的数据 - 您可以通过添加GET参数"format = export"来完成此操作.这将包括特殊".priority"键中每个对象的prirority(请参阅https://www.firebase.com/docs/rest-api.html).然后,您可以在本地按优先级对对象进行排序,然后对要删除的所有对象发出DELETE请求. (2认同)