Dalton
Dalton

Reputation: 137

Providing Custom Params In Express Middleware

I am having a problem with my Node.js app. In short I want to pass custom parameters into my middleware function other than just req, res, and next.

Middleware file:

var DB = require('./DB.js');

function requirePermissions(e) { 
    console.log('nope')
}

module.exports = requirePermissions;

Route:

router.post('/posts', requirePermissions('post_creation'), function(req, res)       {
  var   o       = req.body,
      title   = o.post.title,
      content = o.post.content;

  res.send('made it');
});

I have confirmed that using function requirePermissions(req, res, next) {} will work, but I do not understand how to include my own parameters.

Upvotes: 1

Views: 1450

Answers (2)

jfriend00
jfriend00

Reputation: 708026

You can just create an anonymous function for your middleware that lets you call your actual function with some additional arguments:

router.post('/posts', function(req, res, next) {
      requirePermissions('post_creation', req, res, next);
   }, function(req, res) {
      var o   = req.body,
      title   = o.post.title,
      content = o.post.content;

      res.send('made it');
});

Or, you can use .bind() to preprend arguments:

router.post('/posts', requirePermissions.bind('post_creation'), function(req, res) {
      var o   = req.body,
      title   = o.post.title,
      content = o.post.content;

      res.send('made it');
});

This will call your requirePermissions() functions with four arguments like this:

requirePermissions('post_creation', req, res, next)

Upvotes: 1

Michał Perłakowski
Michał Perłakowski

Reputation: 92669

Your function requirePermissions should return another function which will be the actual middleware:

function requirePermissions(e) {
  if (e === 'post_creation') {
    return function(req, res, next) {
      // the actual middleware
    }
  } else if (e === 'something_else') {
    return function(req, res, next) {
      // do something else
    }
  }
}

You can also do it like that:

function requirePermissions(e) {
  return function(req, res, next) {
    if ('session' in req) {
      if (e === 'post_creation') {
        // do something
      } else if (e === 'something_else') {
        // do something else
      }
    }
  }
}

Upvotes: 3

Related Questions