Xiphias
Xiphias

Reputation: 4726

How can I access server-side variables via Meteor.call()?

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.

Upvotes: 2

Views: 1973

Answers (2)

Tarang
Tarang

Reputation: 75975

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.

Upvotes: 1

Deepsy
Deepsy

Reputation: 3810

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; 

Upvotes: 2

Related Questions