Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use an array of middlewares at express.js

I'm trying to use an array of middlewares. Well, more like a combination of function names and arrays.

Instead of having:

router.post('/editPassword', validate, changePassword, sendConfirmation);

I would like to have something like:

router.post('/editPassword', validate, [changePassword, sendConfirmation] ); 

That would look like:

router.post('/editPassword', validate, doAction ); 

Where doAction would be an array like this:

var doAction = [
   //equivalent of changePassword
   function(req, res, next){
      //whatever
      next();
   },

   //equivalent to the previous sendConfirmation
   function(req, res, next){
      //whatever
   }
]

But it seems it is failing and going back to the validate step after the next() within the first function in doAction.

I'm looking for a way to simplify the middleware chaining including some middleware steps under the same name.

like image 854
Alvaro Avatar asked Mar 17 '17 13:03

Alvaro


2 Answers

I assume the reason you wanted it to look that way is not only for it to appear presentable, but also to be able to reuse the other middleware. In that case, you can create a middleware which runs all other middlewares to do the check for you, and only calls the next function if all validations succeed.

var express = require('express');
var app = express();

function middleware1(req, res, next) {
    if(req.query.num >= 1) {
        next();
    } else {
        res.json({message: "failed validation 1"});
    }
}

function middleware2(req, res, next) {
    if(req.query.num >= 2) {
        next();
    } else {
        res.json({message: "failed validation 2"});
    }
}

function middleware3(req, res, next) {
    if(req.query.num >= 3) {
        next();
    } else {
        res.json({message: "failed validation 3"});
    }
}

function combination(req, res, next) {
    middleware1(req, res, function () {
        middleware2(req, res, function () {
            middleware3(req, res, function () {
                next();
            })
        })
    })
}


app.get('/', combination, function (req, res) {
  res.send('Passed All Validation!');
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

You can test this app by running it then viewing http://localhost:3000/?num=3, changing the value 3 to a lower number, or removing the num parameter.

I'm not sure if this is the proper way to do it, but this is how I've handled my other projects. Let me know what you think.

note: see comments for use case. @robertklep may have a better solution depending on how you want to use middlewares

like image 90
Brian Avatar answered Oct 19 '22 01:10

Brian


Latest version of Express can handle this:

function logOriginalUrl (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}

function logMethod (req, res, next) {
  console.log('Request Type:', req.method)
  next()
}

var logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, function (req, res, next) {
  res.send('User Info')
})

You can review more from this link

like image 20
Misael Abanto Avatar answered Oct 18 '22 23:10

Misael Abanto