Multiple routes with different parameters calling the same resource
Is it possible with expressjs to have multiple routes calling the same resource, something like this:
app.get('/users/:user_id', users.getOne)
app.get('/users/:username', users.getOne)
I would like to be able to call users.getOne, depending on which parameters (: user_id or: username) are used in the get request.
In users.getOne function, how can I determine which one was used and build my query according to it?
exports.getOne = function(req, res){
var queryParams = ? // I need help here
Users
.find(queryParams)
...
Thank!
Possibly related: express.js - single routing handler for multiple routes in one line
source to share
In fact, from the express view, the same route.
No, it is not. One route has a parameter :user_id
, the other has :username
.
This would be the correct solution:
var OBJECT_ID_RE = /^[a-f\d]{24}$/i;
app.param('user_id', function(req, res, next, value, name) {
if (OBJECT_ID_RE.test(value)) {
next()
} else {
next('route')
}
})
app.get('/users/:user_id', users.getOne)
app.get('/users/:username', users.getOne)
app.param
set the necessary condition for calling the route. Thus, when user_id matches the pattern, the first route is called, otherwise the second.
source to share
In quick view, both of these routes will match the same set of request URLs. You only need one of them, and you can call it clearer:
app.get('/users/:key', users.getOne);
//...
// http://stackoverflow.com/a/20988824/266795
var OBJECT_ID_RE = /^[a-f\d]{24}$/i;
exports.getOne = function(req, res) {
var conditions = {_id: req.params.key};
if (!OBJECT_ID_RE.test(req.params.key)) {
conditions = {username: req.params.key};
}
Users.find(conditions)...
If you want to get this pattern across many routes throughout your codebase , you can extract it into a parameter /users/:user
and use app.param
as per @alex answer, but encapsulate the code to find the user and stick with it req.user
, so the actual route handler might just assume that the user was correctly found and loaded at the time of execution, and the 404 processing can also be centralized.
source to share