如何在所有Meteor方法调用的开头添加一个钩子?

时间:2015-01-06 08:45:05

标签: meteor

例如,我想在未登录的客户端调用任何方法时抛出错误,并且我想对登录客户端调用的限制方法进行评级。我希望有一个比

更好的解决方案
Meteor.methods 

  foo: ->
    checkLoggedInAndRate()
    ...

  bar: ->
    checkLoggedInAndRate()
    ...

  ...

1 个答案:

答案 0 :(得分:4)

您可以使用其中一些JavaScript技巧:

首先,让我们定义一个新的Meteor.guardedMethods函数,我们将用它来定义我们的保护方法,它将把常规方法对象和我们想要使用的保护函数作为参数:

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);
    });
};

这个函数简单地遍历方法对象并通过首先调用我们的guard函数然后调用true方法来重新定义底层函数。

这是一个使用我们新定义的方法的快速示例,让我们定义一个虚拟防护功能和一个Meteor方法来测试它:

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

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

此方法的示例输出将为:

> calling testMethod
> inside test method