Safe way to define a function inside Meteor Server?


#1

I want to define a function inside Meteor Server. For example:

if (Meteor.isServer) {
      Meteor.startup(function() {
           addInsert = function(a, b) {
                   var sum = a + b;
                   Caculations.insert({theSum: sum});
           }
      });
}

I will call the function addInsert(1, 2) from a Meteor.method. For example:

Meteor.methods({
    doCalculation: function(a, b) {
         addInsert(1,2);
    }
});

Is this technique safe? I am particularly worried because the addInsert function is a global.
If this is unsafe, please suggest.

Thanks.


#2

What do you mean by “safe”?

  • Is it available at the time it is called? yes
  • Is it available only to methods defined on server? yes
  • Can it be called by anonymous users or any client code? still yes

addInsert cannot be called from the client since it is already defined only on the server. But it can be called anyway because your method can be called from any client.

If you can provide more context to your use-case, perhaps we can come up with a pattern that can fullfill your current safety requirement.


#3

i agree with @serkandurusoy “safe” is a matter of definition. if you are worried that your function is exposed to clients, maybe ‘server only methods’ could be what you are looking for? https://github.com/themeteorchef/server-only-methods


#4

Oh yes, this is a great pattern that I use myself.


#5

Thanks @tomsp This is exactly what I am looking for. Spot on.