Loren
Loren

Reputation: 14846

How can you add a hook to the beginning of all Meteor method calls?

For instance, I'd like to throw an error whenever any method is called by clients who are not logged in, and I want to rate limit methods called by logged-in clients. I'm hoping there's a better solution than

Meteor.methods 

  foo: ->
    checkLoggedInAndRate()
    ...

  bar: ->
    checkLoggedInAndRate()
    ...

  ...

Upvotes: 2

Views: 439

Answers (1)

saimeunt
saimeunt

Reputation: 22696

You can use some of these JavaScript tricks :

First, let's define a new Meteor.guardedMethods function that we'll use to define our guarded methods, it will take as arguments the regular methods object as well as the guard function we want to use :

Meteor.guardedMethods=function(methods,guard){
    var methodsNames=_.keys(methods);
    _.each(methodsNames,function(methodName){
        var method={};
        method[methodName]=function(){
            guard(methodName);
            return methods[methodName].apply(this,arguments);
        };
        Meteor.methods(method);
    });
};

This function simply iterates over the methods object and redefine the underlying function by first calling our guard function and then the true method.

Here is a quick example of using our newly defined method, let's define a dummy guard function and a Meteor method to test it with :

function guard(methodName){
    console.log("calling",methodName);
}

Meteor.guardedMethods({
    testMethod:function(){
      console.log("inside test method");
    }
},guard);

The sample output of this method will be :

> calling testMethod
> inside test method

Upvotes: 5

Related Questions