Firebase聊天 - 删除旧邮件

时间:2013-04-13 17:23:47

标签: firebase

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

为了举例说明我正在寻找的内容,让我告诉你我如何处理私信:

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

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

这是一个示例,说明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",
      }
    }
  }
}

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

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

我希望它有意义!

亲切的问候

聚苯乙烯。非常感谢Firebase团队到目前为止提供的所有帮助,我真的很感激。

1 个答案:

答案 0 :(得分: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.
});

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

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

希望这有帮助!