Firebase chat - removing old messages

后端 未结 1 563
既然无缘
既然无缘 2020-12-07 16:02

I have create a chat with just 1 room, private messages, moderation and everything now and it all works great! While I was testing the chat, I realised that all the messages

相关标签:
1条回答
  • 2020-12-07 16:34

    There are a few different ways to tackle this, some more complicated to implement than others. The simplest solution would be have each user only read the latest 100 messages:

    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.
    });
    

    Your messages list will still contain all messages but it won't affect performance since every client is only asking for the last 100 messages. In addition, if you want to clean up old data, it is best to set the priority for each message as the timestamp of when the message was sent. Then, you remove all the messages older than 2 days with:

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

    Hope this helps!

    0 讨论(0)
提交回复
热议问题