2

I thought that it would be smart to define server-side classes in Meteor that store information about the system. This information should be accessed by selected users. It is not stored in MongoDB, so I think that subscriptions and publications are not an option, as far as I understand them.

This is my simplified approach:

if(Meteor.isServer) {
    serverVar = true; // could depend on server logic
}    

Meteor.methods({
    myMethod: function() {
        if(serverVar) {
            return "secret";
        } else {
            throw Error();
        }
    }
}

Then, on the client:

Meteor.call("myMethod", function(err, res) {
    console.log(res);
}

Unfortunately, I get a ReferenceError that serverVar is not defined. It seems to me that using Meteor.isServer as a condition when defining serverVar breaks the concept. But how can I access server-side variables using Meteor.methods? What kind of approach can solve my problem? Thank you very much!

Update: Thank you for your advice. serverVar could be anything defined on the server, it's not Meteor.isServer. Therefore, I think that just defining serverVar on the client as false would not solve my problem.

Stennie
  • 63,885
  • 14
  • 149
  • 175
Xiphias
  • 4,468
  • 4
  • 28
  • 51

2 Answers2

2
var serverVar = false; // Pre-define serverVar
if(Meteor.isServer) {
   serverVar = true; // could depend on server logic
}    

Meteor.methods({
myMethod: function() {
    if(serverVar) {
        return "secret";
    } else {
        throw Error();
    }
 }
}

Or even

var serverVar = Meteor.isServer; 
Deepsy
  • 3,769
  • 7
  • 39
  • 71
  • Wouldn't this lead to the situation in which `serverVar` is defined on the client and the error does not appear anymore, but it wouldn't be true either. What I want is that I call a method from the client and access server variables. I thought that this is the concept of `Meteor.call` --- that I can access and execute server-side functions and variables. My `serverVar` is just an example, it is not the representation of `Meteor.isServer`. – Xiphias Dec 05 '13 at 09:20
1

Be careful with this. If you're planning on building a scalable app it could be an issue. If your variable is a non user variable which it looks to be. If you set the variable to true & have other servers it wont affect the other servers.

The other issue is if the server crashes/restarts the state is reset

You could store your variables in a collection it might be better to do this. There isn't anything wrong with this.

Tarang
  • 75,157
  • 39
  • 215
  • 276
  • Thank you for pointing that out. In this particular case, I am just trying to limit access to a method to certain circumstances like, let's say, a time method which is only accessible via node.js and therefore a server-side only function. Users could manipulate time on the client, but they cannot on the server. A collection would not make so much sense there. – Xiphias Dec 05 '13 at 09:19