Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow injecting extra arguments to middleware #6

Open
yowu opened this issue May 19, 2020 · 5 comments
Open

Allow injecting extra arguments to middleware #6

yowu opened this issue May 19, 2020 · 5 comments

Comments

@yowu
Copy link

yowu commented May 19, 2020

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;
}
@unbug
Copy link
Owner

unbug commented May 19, 2020

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

@yowu
Copy link
Author

yowu commented May 19, 2020

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

@unbug
Copy link
Owner

unbug commented May 19, 2020

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.

@yowu
Copy link
Author

yowu commented May 22, 2020

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.

@unbug
Copy link
Owner

unbug commented May 22, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants