Files
expressjs.com/en/api/app-param.jade
TJ Holowaychuk 9e957d4e2c Initial commit
2012-07-31 20:33:12 -07:00

73 lines
2.3 KiB
Plaintext

section
h3(id='app.param') app.param([name], callback)
p.
Map logic to route parameters. For example when <code>:user</code>
is present in a route path you may map user loading logic to automatically
provide <code>req.user</code> to the route, or perform validations
on the parameter input.
p.
The following snippet illustrates how the <code>callback</code>
is much like middleware, thus supporting async operations, however
providing the additional value of the parameter, here named as <code>id</code>.
An attempt to load the user is then performed, assigning <code>req.user</code>,
otherwise passing an error to <code>next(err)</code>.
+js.
app.param('user', function(req, res, next, id){
User.find(id, function(err, user){
if (err) {
next(err);
} else if (user) {
req.user = user;
next();
} else {
next(new Error('failed to load user'));
}
});
});
p.
Alternatively you may pass only a <code>callback</code>, in which
case you have the opportunity to alter the <code>app.param()</code> API.
For example the <a href="http://github.com/visionmedia/express-params">express-params</a>
defines the following callback which allows you to restrict parameters to a given
regular expression.
p.
This example is a bit more advanced, checking if the second argument is a regular
expression, returning the callback which acts much like the "user" param example.
+js.
app.param(function(name, fn){
if (fn instanceof RegExp) {
return function(req, res, next, val){
var captures;
if (captures = fn.exec(String(val))) {
req.params[name] = captures;
next();
} else {
next('route');
}
}
}
});
p.
The method could now be used to effectively validate parameters, or also
parse them to provide capture groups:
+js.
app.param('id', /^\d+$/);
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id);
});
app.param('range', /^(\w+)\.\.(\w+)?$/);
app.get('/range/:range', function(req, res){
var range = req.params.range;
res.send('from ' + range[1] + ' to ' + range[2]);
});