Allow injecting extra arguments to middleware
Hi, I am searching for a middleware implement for our project. The solution looks promising.
In our case, sometimes, the middleware need to know some context information to fulfill its task. So, I am wondering if it's possible to enable inject some extra argument to middleware to make the information available. The proposal looks like:
// middleware constructor
// @param {object} extraArgument - data will be injected into middleware
constructor(target, extraArgument, ...middlewareObjects)
// middleware _applyToMethod
middlewares.forEach(middleware =>
typeof middleware === 'function' &&
this._methodMiddlewares[methodName].push(middleware(this._target, this._extraArgument))
);
// middleware implementation
const walk = (target, extraArgument) => next => (...args) => {
// the extraArgument is now accessible in the middleware implementation
return result;
}
In this case, you should use a Middleware object, you could access any context from an object.
Yeah, using object as a closure could be a solution. I prefer the function way because it's easy to share in multiple places.
Actually you could. You could inject a context to the arguments in the first middleware function since the arguments get passed though to all middleware functions. Yes, write a middleware function to control the context, that's the meaning of middleware.
Do you mean passing through middleware chain by next(...args, context)? Then, you need stripe out this context parameter in the last middleware to avoid pollute the target function arguments.
It's a workaround. But, it's not elegant and easy to be broken by others.
It will make sense if you think in middleware.
But there's another option, you could assign the context to your funciton.prototype.context. So you can totally control your middlewares. This is the only solution for function middleware. Feel free to tell me you have a better way.