Skip to content

Instantly share code, notes, and snippets.

@boxofrox
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save boxofrox/9f13550d84058f700185 to your computer and use it in GitHub Desktop.
Save boxofrox/9f13550d84058f700185 to your computer and use it in GitHub Desktop.
Reactive publish-counts with computation example
// don't leak observes in Meteor.publish callback. Define only one instance for server of buyer and distributor ids for reactive counts.
var buyers = new Meteor.Collection(null);
var distributors = new Meteor.Collection(null);
var observer = {
added: function (doc) {
if (isBuyer(doc))
buyers.insert({ _id: doc._id });
else if (isDistrib(doc))
distributors.insert({ _id: doc._id });
},
changed: function (oldDoc, newDoc) {
if (! isBuyer(newDoc))
buyers.remove(newDoc._id);
if (! isDistrib(newDoc))
distributors.remove(newDoc._id);
},
removed: function (doc) {
buyers.remove(doc._id);
distributors.remove(doc._id);
}
};
// observe changes to users query.
Meteor.users.find({
$or: [
{
'roles': 'distributor',
'profile.status': 'PENDING',
'profile.agreedToTOC': true,
},
{
'roles': 'buyer',
'profile.status': 'PENDING',
},
]
}).observe(observer);
function isBuyer (doc) {
return 'buyer' === doc.roles;
}
function isDistrib (doc) {
return 'distributor' === doc.roles;
}
Meteor.publish("pendingReview", function(){
if(Roles.userIsInRole(this.userId, 'compliance')) {
Counts.publish(this, 'remainingDistributors', distributors.find({}));
Counts.publish(this, 'remainingBuyers', buyers.find({}));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment