I am currently exploring a potential difference in coding approaches. Let me illustrate this with an example excerpted from the express documentation: https://expressjs.com/en/guide/using-middleware.html
function logOriginalUrl (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}
function logMethod (req, res, next) {
console.log('Request Type:', req.method)
next()
}
const logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, (req, res, next) => {
res.send('User Info')
})
In the above example, both logOriginalUrl and logMethod serve as middlewares. But what if I were to rewrite it like this:
function logOriginalUrl() {
console.log('Request URL:', req.originalUrl);
}
function logMethod() {
console.log('Request Type:', req.method);
}
app.get('/user/:id', (req, res, next) => {
logOriginalUrl();
logMethod();
res.send('User Info')
})
Would there be any distinction between these two implementations? While this is a basic illustration, it can be extrapolated to various scenarios involving request manipulation or other functionalities.
What sets apart a middleware approach from directly invoking and awaiting a function within a route handler?
In theory, tasks achievable through middleware seem replicateable by simply invoking the same function within the route handler. So, what nuances do I overlook in this transition?