Publications and Reactivity


#1

I have a type of user in my application who can change between companies to impersonate another company as required. The user is then meant to see the data for the client he impersonates.

The clientId is stored in a “role.companyId” field in the user document.

I have userRights helper which allows me to access the company for the current user, both on the client and server. I use this for example in publications to access various objects that are client specific. I believe it would be bad practice to pass the compnayId back to the server via the client.

Meteor.publish("machines.list", function(search="", limit=1000){
  const name = 1;
  const active = 1;
  let selector = search ? {name: new RegExp(search, 'i')} : {};
  selector.companyId = UserRights.getCompanyId();

  const options = {
    fields: {name: 1, active:  1, companyId: 1}, sort: {name: 1}, limit: limit+1};
  console.log(selector);
  return MachinesCollection.find(selector, options); 
});

Unfortunately, this is not reactive, so when a user changes the company they impersonate, they suddenly see the results of the MachinesCollcetion for both the previous and the new company. Is there a recommended way to make these reactive?

PS: I noticed tho package peerlibrary:recative-publish but it is crashing for me due to a non-available ReactiveVar, which I use in my project extensively and I’m thinking there should be a more appropriate way to explicitly invalidate the publication (or subscription)>


#2

The easiest workaround that occurs to me is to pass the companyId as an argument.


#3

Don’t quite get why would it be a bad practice…

In your scenario, including the Company Id as a parameter when subscribing is the best way to trigger the removing of the previously subscribed company data and replace it with the new one.

Of course, the publication should ensure that what is published is in accordance with the user Document, if that is your business rule.


#4

What exactly is UserRights, and can you show the code for UserRights.getCompanyId()? Reactivity on the server relies on cursor observers and so I think the nicest way to solve this would require you to use a cursor instead of just returning the companyId.