Stopping subscription on the server


#1

Let’s say a user can only subscribe to a certain publication in case he has been given access to it.

So in pseudo code this could be something like

Meteor.publish("taskDetails", function (id) {
  if(hasAccessToTask(this.userid,id))
     return Tasks.find(id);
});

However, this access could later be revoked, after which the user should stop getting updates.
What is the best pattern to do this?


#2

This is really a subset of the problem discussed at https://www.discovermeteor.com/blog/reactive-joins-in-meteor/. I’m a fan of using the reywood:publish-composite package for this particular use case. For example, if the user’s access was determined by some attribute set on the user document, you could try this:

Meteor.publishComposite('taskDetails', function(id) {
  var userId = this.userId;
  return {
    find: function() {
      return Meteor.users.find(userId);
    },
    children: [{
      find: function(user) {
        if (hasAccessToTask(user, id))
          return Tasks.find(id);
      } 
    }]
  };
});

When the user document is updated (i.e. when the cursor results from the first find changes), then the child find (and the hasAccessToTask function) is re-run and the old publication is stopped.