NodeJS Express middleware abstraction
NodeJS Express https://expressjs.com/ is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
Middleware functions https://expressjs.com/en/guide/using-middleware.html are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Abstraction
Middleware is flexible. You can use anonymous or named functions, but the best thing is to abstract request handlers into external modules based on the functionality. Even this is straightforward, sometimes we need to pass a param(s) to the exported module functions. Param could be even a callback function. You can find below a simple example.
./middlewares/middleware.js
requiredParamHandler = function(param) {
return function (req, res, next) {
// Use param
}
}exports.requiredParamHandler = requiredParamHandler;
app.js
let middleware = require('./middlewares/middleware');app.get('/api/v1', middleware.requiredParamHandler(param));
