Publications / Subscriptions Question

Let’s say I have a publication like this:

Meteor.publish('leads', function() {
  if (! this.userId) {
    return;
  }
  check(this.userId, String);
  return Leads.find({ userId: this.userId });
});

And I’m subscribing to that data like this:

Leads.find({}, { sort: { createdAt: -1 }, limit: 50 })

I’m wondering what others (read: better coders than me!) think of the practice of not passing in a user when making the query on the client. The published data is only for the currently authenticated user so do we need to bother passing in the client-side user too, particularly given data from the client can’t be trusted?

The only thing I can think of is that it’s clearer in the code precisely what data the query is requesting.

Also, I’m guessing I don’t need to run check on the user ID here. It’s always from the server, right?

Hi,

you are correct that you dont need to pass it as u r using server one.
check for string should not be needed.

And consider using limit on publication find, not only client side.
Pagination is your friend, especially on mobile devices and not superspeed internetz.

if(Meteor.isServer) {
	Meteor.publish('someData', function() {
		if(this.userId) {
			Collection.find({userId: this.userId});
		} else {
			this.ready();
		}
	});
}

if(Meteor.isClient) {
	var myDataSub;

	Tracker.autorun(function() {
		if(Meteor.userId()) {
			myDataSub = Meteor.subscribe('someData');
		} else {
			if(myDataSub) myDataSub.stop();
		}
	})
}

Cool. Thank you, both.

From @mrzafod:

if(Meteor.isClient) {
  	var myDataSub;

  Tracker.autorun(function() {
    		if(Meteor.userId()) {
      			myDataSub = Meteor.subscribe('someData');
    		} else {
      			if(myDataSub) myDataSub.stop();
    		}
  	});
}

It works, but the following code has (almost) the same effect and is more efficient:

if(Meteor.isClient) {
  Meteor.subscribe('someData');
}

The explanation lies here (second line).