Skip to content
Myr

Doc cleanup

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 0faac20 · Browse files · 1 file+6 added−6 removed
This commit

State

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

Diff stats

1 file+6 added−6 removed

  • other:+6 added−6 removed

1 file+6 added−6 removed

modified:docs/guide.md+6 added-6 removed
201 unmodified lines
202Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 203204 app.get('/user/:id', function(req, res, next){205 loadUser(req.params.id, function(err, user){206 if (err) return next(err);207 res.send('Viewing user ' + user.name);206 if (err) return next(err);207 res.send('Viewing user ' + user.name);208 });209 });210211To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time.
16 unmodified lines
228Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.229230 function andRestrictToSelf(req, res, next) {231 req.authenticatedUser.id == req.user.id232 ? next()233 : next(new Error('Unauthorized'));232 ? next()233 : next(new Error('Unauthorized'));234 }235 236 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){237 res.send('Editing user ' + req.user.name);
3 unmodified lines
241242 function andRestrictTo(role) {243 return function(req, res, next) {244 req.authenticatedUser.role == role245 ? next()246 : next(new Error('Unauthorized'));245 ? next()246 : next(new Error('Unauthorized'));247 }248 }249 250 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){
663 unmodified lines