Using a session.get variable in Publish/Subscribe

286 views Asked by At

I'm trying to display a filterable database of clients that only loads the content required. I've got two variables (selected from dropdowns) that set two sessions (country_plugin and vertical_plugin). I then want to display the content that meets those requirements.

The code below works perfectly if you're not worried about autopublish, but I have no idea how to achieve the same with pub/sub.

So, in short, how can I use session.get and if statements here?

filteredclients: function () {
            var clientVerticalPicked = Session.get('vertical_plugin');
        var clientCountryPicked = Session.get('country_plugin');
            if (Session.get("country_plugin") === "none"){
                    return Clients.find({dealVerticalLink: clientVerticalPicked}, {sort: {dealMRR: -1}, limit:10});
            } else if (Session.get("vertical_plugin") === "none"){
                    return Clients.find({dealCountry: clientCountryPicked}, {sort: {dealMRR: -1}, limit:10});
            } else {
                    return Clients.find({$and:[{dealVerticalLink: clientVerticalPicked},{dealCountry: clientCountryPicked}]}, {sort: {dealMRR: -1}, limit:10});
            }
        }
1

There are 1 answers

0
Michael Paddock On

Session variables are only defined on the client, so you won't be able to access them from within the publish function. You can do your subscribe in a Tracker.autorun on the client, and pass the Session variables into the publish function:

Tracker.autorun(function() {
    Meteor.subscribe('filteredclients', Session.get('vertical_plugin'), Session.get('country_plugin'))
});

And on the server:

Meteor.publish('filteredclients', function(vertical_plugin, country_plugin) {
    if(country_plugin === "none") { return ... }
});

etc. Then your Clients.find() on the client should only contain the records you want.