How to optimize an Express.js route?
I'm developing a reserved area that has the follow few pages:
/dashboard
/dashboard/profile
/dashboard/user
/dashboard/view
that's a simple user control panel. At the moment i have four routes:
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 */ });
I would like to optimize it because in each of the above routes i have to call this function at the beginning:
authorized(req, function(auth){
if (!auth) return next(errors.fire(403));
/* route code */
});
This function checks if the user is logged, so i need to call it on every reserved page.
I would do something like:
app.all('/dashboard/*', function(req, res, next) {
authorized(req, function(auth){
if (!auth) return next(errors.fire(403));
开发者_如何学编程 res.render(something, {})
});
});
the something
inside the res.render call has to be the view (page) I need to open.
I want to call it ONE time, to remove redundant code.
That could be the home of the panel (if the user wants /dashboard) or the page (if the user wants a page inside /dashboard like /dashboard/profile) in the last case i need to render 'profile' view.
(I have to do a check before pass the view to render(), because if someone try /dashboard/blablablabla it should be a problem.)
Thank you
You can pass that function to each route as a route middleware, check http://expressjs.com/guide.html#route-middleware for more info. The idea would be this:
function mustBeAuthorized(req, res, next){
/* Your code needed to authorize a user */
}
And then in each route:
app.all('/dashboard', mustBeAuthorized, function(req, res, next) { /* Code */ });
Or if your logic depends on a certain role for each route, you can make the route middleware like this:
function mustBeAuthorizedFor(role){
return function(req, res, next){
/* Your code needed to authorize a user with that ROLE */
};
}
And then call it right away:
app.all('/dashboard', mustBeAuthorizedFor('dashboard'), function(req, res, next) { /* Code */ });
Isn't it:
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, {})
});
});
精彩评论