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

How can you remove middleware from a container at runtime? #1100

Open
d1820 opened this issue Jun 29, 2019 · 1 comment
Open

How can you remove middleware from a container at runtime? #1100

d1820 opened this issue Jun 29, 2019 · 1 comment

Comments

@d1820
Copy link

d1820 commented Jun 29, 2019

As i apply middleware to a global container in a unit testing scenario i want to remove the middleware after each test run so i can reset the container properly

Expected Behavior

It should work where i can pass the middleware function reference into a removeMiddleware() method or even a key if storing the middleware references in a Map

Current Behavior

No method seems to exist to remove middleware aside from creating a new container.

Possible Solution

Add a new method to removeMiddleware
or remove middleWare as an option on an unbindAll(includeMiddleware: boolean)

@tonyhallett
Copy link
Contributor

You can set container._middleware to undefined. Another solution

abstract class ToggleMiddleware{
            
            abstract actualMiddleware:interfaces.Middleware
            private middlewareOn=true;
            toggle(): void {
                this.middlewareOn=!this.middlewareOn;
                this.toggled(this.middlewareOn);
            }
            //reset state if desired
            toggled(on:boolean){}
            middleware:interfaces.Middleware=(next)=>{
                return (args:interfaces.NextArgs)=>{
                    if(this.middlewareOn){
                       return this.actualMiddleware(next)(args);
                    }
                    
                    return next(args);
                }
            }
        }
class GetCountToggleMiddleware extends ToggleMiddleware{
            getCount=0;
            actualMiddleware:interfaces.Middleware=(next)=>{
                return (nextArgs)=>{
                    this.getCount++;
                    return next(nextArgs);
                }
            }
        }

const getCountMiddleware=new GetCountToggleMiddleware();
container.applyMiddleware(getCountMiddleware.middleware);
//some container
 const c1=container.get('C1');
//turn off
 getCountMiddleware.toggle();
//container still works
 const c2=container.get('C2');

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

No branches or pull requests

2 participants