2011-08-13 78 views
4

我開發具有如下幾頁預留區域:如何優化Express.js路線?

/dashboard 
/dashboard/profile 
/dashboard/user 
/dashboard/view 

這是一個簡單的用戶控制面板。目前,我有四個途徑:

app.all('/dashboard', function(req, res, next) { /* Code */ }); 
app.all('/dashboard/profile', function(req, res, next) { /* Code */ }); 
app.all('/dashboard/user', function(req, res, next) { /* Code */ }); 
app.all('/dashboard/view', function(req, res, next) { /* Code */ }); 

我想優化它,因爲在上述各路線我已經在開始的時候調用這個函數的:

authorized(req, function(auth){ 
    if (!auth) return next(errors.fire(403)); 
    /* route code */ 
}); 

此函數檢查用戶已登錄,所以我需要在每個保留頁面上調用它。

我會做這樣的事情:

app.all('/dashboard/*', function(req, res, next) { 

    authorized(req, function(auth){ 
     if (!auth) return next(errors.fire(403));   
     res.render(something, {})  
    }); 

}); 

something的res.render調用內部必須是我需要打開視圖(頁)。

我想叫它ONE時間,刪除多餘的代碼。

這可能是面板的家(如果用戶想要/儀表板)或頁面(如果用戶想要一個頁面裏面/儀表板像/儀表板/配置文件)在最後一種情況下,我需要渲染'配置文件'視圖。

(我必須做檢查之前,通過視圖渲染(),因爲如果有人試圖/儀表板/ blablablabla它應該是一個問題。)

謝謝

+0

使用中間件。 – Raynos

回答

2

不是吧:

app.get('/dashboard/:page?', function(req, res, next){ 
    var page = req.params.page; 
    if (! page) { 
     page = "dash-index" 
    } 

    authorized(req, function(auth){ 
     if (!auth) return next(errors.fire(403));   
     res.render(page, {})  
    }); 
}); 
7

您可以傳遞函數作爲路由中間件每個路由,檢查http://expressjs.com/guide.html#route-middleware獲取更多信息。這個想法是這樣的:

function mustBeAuthorized(req, res, next){ 
    /* Your code needed to authorize a user */ 
} 

然後在每條路線:

app.all('/dashboard', mustBeAuthorized, function(req, res, next) { /* Code */ }); 

或者,如果你的邏輯取決於每條路線有一定的作用,可以使路線中間件這樣的:

function mustBeAuthorizedFor(role){ 
    return function(req, res, next){ 
    /* Your code needed to authorize a user with that ROLE */ 
    }; 
} 

然後調用它的時候了:

app.all('/dashboard', mustBeAuthorizedFor('dashboard'), function(req, res, next) { /* Code */ });