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

Lor*_*ren 2 meteor

例如,每当未登录的客户端调用任何方法时,我都想抛出错误,并且我想对登录客户端调用的方法进行速率限制。我希望有比这更好的解决方案

Meteor.methods 

  foo: ->
    checkLoggedInAndRate()
    ...

  bar: ->
    checkLoggedInAndRate()
    ...

  ...
Run Code Online (Sandbox Code Playgroud)

sai*_*unt 5

您可以使用其中一些 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);
    });
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

Meteor.guardedMethods({
    testMethod:function(){
      console.log("inside test method");
    }
},guard);
Run Code Online (Sandbox Code Playgroud)

此方法的示例输出将是:

> calling testMethod
> inside test method
Run Code Online (Sandbox Code Playgroud)