Managing unread messages in firebase chat

后端 未结 2 1942
别跟我提以往
别跟我提以往 2021-01-04 21:03

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 wi

相关标签:
2条回答
  • 2021-01-04 21:25

    Don't reinvent the wheel :) Full working solution with code sample including unread messages by the Firebase team at https://firechat.firebaseapp.com

    0 讨论(0)
  • 2021-01-04 21:49

    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.

    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:

    • how many messages your user has read
    • how many messages exist
    • the difference is the number of unread messages

    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());
    });
    
    0 讨论(0)
提交回复
热议问题