Reputation: 5487
I'm creating several routes with the same functionality. Is there a better DRY method to creating these routes instead of copying and pasting them like I have below?
app.get('/adminoverviews', function(req, res, next){
if(!req.isAuthenticated()) {
res.status(403);
res.redirect('/login');
res.end();
}else{
next();
}
},function(req, res) {
res.render('index.ejs',{
bootstrappedUser: req.user,
page: 'admin'
})
});
app.get('/adminoverviews/:id', function(req, res, next){
if(!req.isAuthenticated()) {
res.status(403);
res.redirect('/login');
res.end();
}else{
next();
}
},function(req, res) {
res.render('index.ejs',{
bootstrappedUser: req.user,
page: 'admin'
})
});
Upvotes: 0
Views: 98
Reputation: 5848
I'd first seperate authenticate
into it's own declaration
var authenticate = function(req, res, next) {
if(!req.isAuthenticated()) {
res.status(403);
res.redirect('/login');
res.end();
} else {
next();
}
}
If your route function is different for /adminoverviews
vs. /adminoverviews/:id
:
app.get('/adminoverviews', authenticate, function(req, res) {
}
app.get('/adminoverviews/:id', authenticate, function(req, res) {
}
Otherwise you may to do something similar to what was done with authenticate
You may need to do some validation with :id
. I'd suggest using router.param
.
http://expressjs.com/api#router.param
Upvotes: 1