Skip to content
Myr

Route precondition docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent d3abcaf · Browse files · 3 files+157 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+157 added−0 removed

  • other:+157 added−0 removed

3 files+157 added−0 removed

modified:docs/guide.1+79 added
695 unmodified lines
696.697.P698The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.699.700.SS "Route Preconditions"701Route placeholder pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR,we might typically do something like below:702.703.IP "" 4704.705.nf706707app\.get(\'/user/:userId\', function(req, res, next){708 User\.get(req\.params\.userId, function(err, user){709 if (err) return next(err);710 res\.send(\'user \' + user\.name);711 });712});713.714.fi715.716.IP "" 0717.718.P719With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.720.721.IP "" 4722.723.nf724725app\.param(\'userId\', function(req, res, next, id){726 User\.get(id, function(err, user){727 if (err) return next(err);728 if (!user) return next(new Error(\'failed to find user\'));729 req\.user = user;730 next();731 });732});733.734.fi735.736.IP "" 0737.738.P739Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:740.741.IP "" 4742.743.nf744745app\.get(\'/user/:userId\', function(req, res){746 res\.send(\'user \' + req\.user\.name);747});748.749.fi750.751.IP "" 0752.753.P754For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument)\. Any errors thrown will be passed to \fInext(err)\fR\.755.756.IP "" 4757.758.nf759760app\.param(\'number\', function(n){ return parseInt(n, 10); });761.762.fi763.764.IP "" 0765.766.P767We may also apply the same callback to several placeholders, for example a route GET \fI/commits/:from\-:to\fR are both numbers, so we may define them as an array:768.769.IP "" 4770.771.nf772773app\.param([\'from\', \'to\'], function(n){ return parseInt(n, 10); });774.775.fi776.777.IP "" 0778.779.SS "View Rendering"780View filenames take the form \fINAME\fR\.\fIENGINE\fR, where \fIENGINE\fR is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.render(str, options)\fR to comply with Express, however \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by jade\.781.782.P
1163 unmodified lines
modified:docs/guide.html+42 added
187 unmodified lines
188<li><a href="#Middleware">Middleware</a></li>189<li><a href="#Route-Middleware">Route Middleware</a></li>190<li><a href="#HTTP-Methods">HTTP Methods</a></li>191<li><a href="#Error-Handling">Error Handling</a></li>192<li><a href="#Route-Preconditions">Route Preconditions</a></li>193<li><a href="#View-Rendering">View Rendering</a></li>194<li><a href="#View-Partials">View Partials</a></li>195<li><a href="#Template-Engines">Template Engines</a></li>196<li><a href="#Session-Support">Session Support</a></li>
505 unmodified lines
702703<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>704is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>705706<h3 id="Route-Preconditions">Route Preconditions</h3>707708<p>Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>,we might typically do something like below:</p>709710<pre><code>app.get('/user/:userId', function(req, res, next){711 User.get(req.params.userId, function(err, user){712 if (err) return next(err);713 res.send('user ' + user.name);714 });715}); 716</code></pre>717718<p>With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>719720<pre><code>app.param('userId', function(req, res, next, id){721 User.get(id, function(err, user){722 if (err) return next(err);723 if (!user) return next(new Error('failed to find user'));724 req.user = user;725 next();726 });727});728</code></pre>729730<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>731732<pre><code>app.get('/user/:userId', function(req, res){733 res.send('user ' + req.user.name);734});735</code></pre>736737<p>For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to <em>next(err)</em>.</p>738739<pre><code>app.param('number', function(n){ return parseInt(n, 10); });740</code></pre>741742<p>We may also apply the same callback to several placeholders, for example a route GET <em>/commits/:from-:to</em> are both numbers, so we may define them as an array:</p>743744<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });745</code></pre>746747<h3 id="View-Rendering">View Rendering</h3>748749<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name750of the module that will be required. For example the view <em>layout.ejs</em> will
713 unmodified lines
modified:docs/guide.md+36 added
418 unmodified lines
419420The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_421is present, which is useful for developing apps that rely heavily on client-side JavaScript.422423### Route Preconditions424425Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_,we might typically do something like below:426427 app.get('/user/:userId', function(req, res, next){428 User.get(req.params.userId, function(err, user){429 if (err) return next(err);430 res.send('user ' + user.name);431 });432 }); 433434With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.435436 app.param('userId', function(req, res, next, id){437 User.get(id, function(err, user){438 if (err) return next(err);439 if (!user) return next(new Error('failed to find user'));440 req.user = user;441 next();442 });443 });444445Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:446447 app.get('/user/:userId', function(req, res){448 res.send('user ' + req.user.name);449 });450451For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to _next(err)_.452453 app.param('number', function(n){ return parseInt(n, 10); });454455We may also apply the same callback to several placeholders, for example a route GET _/commits/:from-:to_ are both numbers, so we may define them as an array:456457 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });458459### View Rendering460461View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name462of the module that will be required. For example the view _layout.ejs_ will
624 unmodified lines