user9945420
user9945420

Reputation:

chain middleware functions in custom function

I know that I can chain middleware functions after passing in the route like

const express = require('express');
const router = express.Router();
router.post('/', middlewareFunction1, middlewareFunction2, controllerFunction);
module.exports = router;

I would like to know if it's possible to call only one function (called gateway)

router.post('/', gatewayFunction1);

and this function is able to chain all those methods

const controller = require('../controllers/controller');

function gatewayFunction1(request, response, next) {
  // validate route
  // do other middleware stuff
  // call controller.function1
}

module.exports = {
  gatewayFunction1,
};

Why would I do that? I was thinking about separating the middleware logic from the routes. This gateway should just get executed after routing and before calling the router.

I tried to return an array of functions (example code)

function gatewayFunction1(request, response, next) {
  return [(request, response, next) => {
    console.log('called middleware 1');
    next();
  }, (request, response, next) => {
    console.log('called middleware 2');
    next();
  }, (request, response, next) => {
    response.status(200).json({
      message: 'that worked',
    });
  }];
}

but when I call this api route I get no response

Could not get any response

so it keeps loading forever. Is there a way to chain these middleware functions within another function?

Upvotes: 1

Views: 1009

Answers (2)

lx1412
lx1412

Reputation: 1200

Your gatewayFunction1 does nothing except returns an array. Just use router.

const express = require('express');
const gatewayFunction1 = express.Router();
gatewayFunction1.use(middlewareFunction1, middlewareFunction2, controllerFunction);
module.exports = gatewayFunction1;

Then

const gatewayFunction1 = require('...');  // where you define gatewayFunction1
router.post('/', gatewayFunction1);

Upvotes: 1

Iman Rb
Iman Rb

Reputation: 797

Middleware should be a function and you are returning an array.If next function is not called it will get stuck. I don't like the whole idea combining them but I think the best way is to import all your middleware functions in one function and call them individually then use that function as your combined middleware.

Upvotes: 0

Related Questions