npr
npr

Reputation: 4775

expressjs route methods before and after

How to add middleware functions to each of expressjs route functions ? Most of route functions which turn out to be CRUD on database have standard before and after statements - is there a way to have before and after for route functions.

  app.route('/api/resources').all(projectsPolicy.isAllowed)
    .get(resources.list)
    .post(resources.create);

Upvotes: 1

Views: 251

Answers (2)

adeneo
adeneo

Reputation: 318322

Express supports multiple callbacks, as in

app.get('/example/b', function (req, res, next) {
   // do something here, like modify req or res, and then go on

   next();
}, function (req, res) {

   // get modified values here

});

which could also be written as

app.route('/api/resources', projectsPolicy.isAllowed).get(...

assuming the middlewares isAllowed() function calls next() etc.

Upvotes: 1

Jacopo Brovida
Jacopo Brovida

Reputation: 465

I think it's possible to make this:

app.route('/api/resources').all(projectsPolicy.isAllowed)
.get(before,resources.list,after)
.post(before,resources.create,after);

where before and after are functions

Upvotes: 2

Related Questions