20
loading...
This website collects cookies to deliver better user experience
Can we create a middleware out of any function, so that developers don't have to worry about the tricky syntax and testing of middlewares
//generic express middleware syntax
const middleware = (req, res, next) => {
// EXECUTION LOGIC
next(); // This is where the control leaves this middleware and moves to next item in the queue, which could be another middleware, or the final controller etc
}
EXECUTION LOGIC
dynamically. //withMiddleware.js
//Higher Order Function
const withMiddleware = (func) => {
return (req, res, next) => {
func(); //func has the EXECUTION LOGIC
next();
}
}
module.export = withMiddleware;
const withMiddleware = require('./withMiddleware');
const funcOne = () => {
//YOUR BUSINESS LOGIC
}
const funcTwo = () => {
//YOUR ANOTHER BUSINESS LOGIC
}
const middlewareOne = withMiddleware(funcOne);
const middlewareTwo = withMiddleware(funcTwo);
//use this middlewares in a standard way.
app.get("/path", middlewareOne, middlewareTwo, (req, res)=>{
//further execution, if any
res.send({});
})