Middleware composition
Closed this issue · 3 comments
I'm using a composition model for adding multiple layers of middleware, just wondering if you see any downside to this? I'm doing this on a current application and wanting to try using Polkadot instead of my current serverless setup.
Based off of the with-middleware
example, I'm doing something more like this:
const compose = (...fns) => fns.reduce((a, b) => (...val) => a(b(...val)))
const withUser = fn => (req, res, ...params) => {
// TODO: some logic to check if is a User
fn(req, res, ...params)
}
const withHeaders = fn => (req, res, ...params) => {
res.setHeader('X-Foobar', 'Hello world')
res.setHeader('Cache-Control', 'public, max-age=30')
fn(req, res, ...params)
}
const withFns = compose(withUser, withHeaders)
module.exports = withFns(async (req, res) => {
try {
res.statusCode = 200
res.end('ok')
} catch (err) {
// Error handler
res.statusCode = 400
return err.message || err
}
})
Hey~! Nope, that's totally fine! However you may be interested in using something like @arr/reduce
to squeeze out every last bit of speed (perf comparison).
Also, you may be interested in polkadot-middleware
from @TehShrike which effectively is the same as your compose
and I know he's used it often with success.
Closing this, but don't hesitate with any follow up :)
Thanks! I've just started using @arr
utils in some other projects, so good reminder.
I'm assuming that his compose function should be a bit quicker too due to having less object spreads?
Appreciate the response!
Less spreads and isn't creating new or invoking as many functions during iteration. Likely not a deal breaker either way, but is technically less work being done :)
No problem!