js-middleware icon indicating copy to clipboard operation
js-middleware copied to clipboard

Allow injecting extra arguments to middleware

Open yowu opened this issue 5 years ago • 5 comments

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;
}

yowu avatar May 19 '20 02:05 yowu

In this case, you should use a Middleware object, you could access any context from an object.

unbug avatar May 19 '20 06:05 unbug

Yeah, using object as a closure could be a solution. I prefer the function way because it's easy to share in multiple places.

yowu avatar May 19 '20 10:05 yowu

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.

unbug avatar May 19 '20 12:05 unbug

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.

yowu avatar May 22 '20 15:05 yowu

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.

unbug avatar May 22 '20 15:05 unbug