keune
keune

Reputation: 5795

firebase: get records with dates greater than now

I'm using Firebase for an admin panel which has multiple users. Whenever a new question is added, everyone in the panel gets alerted immediately.

It's working fine, but the way i implemented it doesn't feel right. Here's what i'm doing:

dataRef.auth(token, function(error, result) {
    if (error) {
        console.log("Login Failed!", error);
    } else {
        var started = new Date();
        dataRef.on('child_added', function(snapshot) {
            var message = snapshot.val();
            var t = message.date.split(/[- :]/);
            var lastChildDate = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
            if(lastChildDate > started) {
                // alert the user
            }
        });
    }
});

And this is the data structure. It only has one field:

{date: "2013-06-14 16:45:10"}

This brings all the records in that base. A child_added event gets fired for all records. I then check if it's created after the page is loaded, and alert the user accordingly. But the clients only need to be alerted for children that are added from now on. How can i get rid of that unnecessary load? I've checked the documentation, but couldn't find an answer.

Upvotes: 1

Views: 2785

Answers (1)

Andrew Lee
Andrew Lee

Reputation: 10195

There's a few ways to solve this issue.

1) Encode the timestamp at which the event occurred in the priority of the new child, and then use "startAt" to prune older elements.

Make sure your encoding of time sorts lexigraphically in time order.

For example:

ref.startAt("2013-06-14 10:11:13").on(...);

When generating the timestamped items, you'll want to use the Firebase server time so everyone is working off of the same clock. See serverTimeOffset: https://www.firebase.com/docs/managing-presence.html

2) Have a different event queue for every user, and have users' clients remove elements from the queue once they've seen them.

This solution is best in cases where each user might receive different notifications, such as in a social network.

Upvotes: 1

Related Questions