Accessing headers within collection hooks


#1

I’d like to access header information inside of collection hooks (which are called from publication functions).

Is this possible?

Here’s what I’ve tried so far, but it doesn’t seem to be working:

Meteor.startup(function() {
  Posts.before.find(function(userId, selector, options) {
    var self = this;
    console.log(headers.get(self, 'host'));
  });
});

And the exception thrown:

Exception from sub posts id pXwknxFQWfuwWjxhy Error: Call headers.get(this) only from within a method or publish function.  With callbacks / anonymous functions, use: var self=this; and call headers.get(self);
I20150613-14:53:11.801(-4)?     at checkSelf (packages/gadicohen:headers/headers-server.js:73:1)
I20150613-14:53:11.801(-4)?     at Object.headers.get (packages/gadicohen:headers/headers-server.js:82:1
...

Any help is appreciated! Thanks in advance.


#2

Same error if you use console.log(headers.get(this, 'host')); ?


#3

Yup. Strangely enough, if I define my hook within a publication and use var self = this; within the publication scope it works.

But that causes other larger issues in my application.


#4

I’m essentially trying to grab different objects from a collection based on the hostname (for a scalable system), and it sort of works by defining my hook inside of a null publication.

If I access my site from two different tabs from two different hostnames, the second page load will overwrite the headers used to modify the collection query and then via DDP the incorrect collection objects are shown on both tabs.

Meteor.startup(function() {
  Meteor.publish(null, function () {
    var self = this;
    Posts.before.find(function(userId, selector, options) {
      var host = headers.get(self, 'host');
      selector.host = host;
    });
    this.ready();
  });
});