Jeroen Berrevoets
Jeroen Berrevoets

Reputation: 15

Make a meteor publication reactive to time

I'm having a little trouble figuring out how to make a subscription reactive to a certain publication query.

My publication is as follows:

Meteor.publish('allData', function(){
    return Data.find({TTL: {$gt: new Date()}})
})

As you can see, the documents contain a TTL field. As long as the Time To Live is still greater that the current time, it can be sent to the client, if not, it shouldn't.

the subscription:

this.autorun(() => {
    this.subscribe('allData')
})

On the initial load, all data is fine, but whenever the TTL expires, the document remains on the client unless I reload the page. Is there anyway to handle this reactively, making the expired documents disappear from the client?

Upvotes: 1

Views: 489

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20227

Use the remcoder:chronos package to make time itself reactive then do:

client:

Meteor.subscribe('allDataSince',Chronos.currentTime());

server:

Meteor.publish('allDataSince', t => Data.find({ TTL: { $gt: t }}));

Upvotes: 0

Teetow
Teetow

Reputation: 455

A combination of ReactiveVar and an autorun did the trick for me. It's possible that this is overkill, but it works.

let cutoffTimestamp = new ReactiveVar();

Meteor.setInterval(function() {
    cutoffTimestamp.set(Date.now() - 1);
}, 60000);

Meteor.publish("myPub", function() {
    this.autorun(function() {
        return myCollection.find({ timestamp: { $gte: cutoffTimestamp.get(); } });
    });
});

Upvotes: 2

Related Questions