有没有办法自定义Meteor方法,在运行所需方法之前,会检查用户是否已登录,然后再继续使用该方法?
例如:
Meteor.call('foo',bar,function(){}); //client.js
Meteor.methods({
//check the user if logged in here before proceeding to foo or bazz function
'foo':function(bar)
//logic here
'bazz':function(fizz)
//logic here
});
我能做到
foo函数中的this.userId
要检查,但我的观点是在执行之前登录所有方法时应用检查。
答案 0 :(得分:0)
这是一个很好的问题。使用当前的API,我认为你无法开箱即用。但是,您可以在将所有函数传递给Meteor.methods
之前将其包装起来。如果我们定义requireLogin
这样的函数:
var requireLogin = function(methods) {
_.each(methods, function(value, key) {
methods[key] = _.wrap(value, function() {
// don't bother calling the function if the user isn't logged in
if (!this.userId)
throw new Meteor.Error(401, 'You must be logged in.');
// the wrapped function is always the first argument
var wrappedFunc = arguments[0];
// convert the other arguments into an array
var args = arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : [];
// call the wrapped function with args and the correct context
return wrappedFunc.apply(this, args);
});
});
return methods;
};
然后,我们可以在调用requireLogin
之前使用Meteor.methods
。例如:
Meteor.methods(requireLogin({
foo: function(n) {
console.log("foo: " + n);
},
bar: function(n) {
console.log("bar: " + n);
}
}));
如果您想对所有电话执行此操作,可以通过将Meteor.methods
本身包裹起来使用requireLogin
来进一步改善这一点。