2014-03-19 153 views
2

我已經打了有流星一段時間,現在已經發布到客戶端Meteor.methods({...})只允許在用戶登錄

現在我檢查的一些服務器的方法來運行流星服務器的方法每個方法的開始,如果用戶登錄。是否有可能更多的面向方面編寫代碼,並檢查另一個更集中的地方?類似Meteor.Collection.allow檢查的方式?我希望用戶能夠登錄大多數的方法,如果不是全部的話。

服務器上可能有一些執行管道,我可以插入函數來執行此操作嗎?

回答

1

我想這樣做一段時間。

這是我到目前爲止有:

// function to wrap methods with the provided preHooks/postHooks. Should correctly cascade the right value for `this` 
function wrapMethods(preHooks, postHooks, methods){ 
    var wrappedMethods = {}; 
    // use `map` to loop, so that each iteration has a different context 
    _.map(methods, function(method, methodName){ 
    wrappedMethods[methodName] = makeFunction(method.length, function(){ 
     var _i, _I, returnValue; 
     for (_i = 0, _I = preHooks.length; _i < _I; _i++){ 
     preHooks.apply(this, arguments); 
     } 
     returnValue = method.apply(this, arguments); 
     for (_i = 0, _I = postHooks.length; _i < _I; _i++){ 
     postHooks.apply(this, arguments); 
     } 
     return returnValue; 
    }); 
    }); 
    return wrappedMethods; 
} 

// Meteor looks at each methods `.length` property (the number of arguments), no decent way to cheat it... so just generate a function with the required length 
function makeFunction(length, fn){ 
    switch(length){ 
    case 0: 
     return function(){ return fn.apply(this, arguments); }; 
    case 1: 
     return function(a){ return fn.apply(this, arguments); }; 
    case 2: 
     return function(a, b){ return fn.apply(this, arguments); }; 
    case 3: 
     return function(a, b, c){ return fn.apply(this, arguments); }; 
    case 4: 
     return function(a, b, c, d){ return fn.apply(this, arguments); }; 
    // repeat this structure until you produce functions with the required length. 
    default: 
     throw new Error("Failed to make function with desired length: " + length) 
    } 
} 

如果你想要把這個給單獨的文件/包,你需要改變function wrapMethods(...){...}wrapMethods = function(...){...}

使用示例,檢查用戶在方法調用之前有效:

function checkUser(){ 
    check(this.userId, String); 
} 
Meteor.methods(wrapMethods([checkUser], [], { 
    "privilegedMethod": function(a, b, c){ 
    return true; 
    } 
}));