Skip to content

Instantly share code, notes, and snippets.

@anotherxx
Last active November 6, 2017 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anotherxx/bb641b131d58973c0c938358f778c5bb to your computer and use it in GitHub Desktop.
Save anotherxx/bb641b131d58973c0c938358f778c5bb to your computer and use it in GitHub Desktop.
Middleware js Laravel like implementation
let middlewares = [{
handle(requesst , next)
{
console.log(`Username is: ${request.name}`);
next(request);
}
},
{
handle(request ,next)
{
console.log(`request Password is: ${request.password}`)
next(request);
}
},
{
handle(request ,next)
{
/** First middleware in stack , do some logic for example check credentianls are valid e.t.c*/
console.log("Request is Come: Start processing ...");
next(request);
}
}
];
class Pipeline
{
constructor()
{
this.method = 'handle';
}
send(passable)
{
this.passable = passable;
return this;
}
through(middlewares)
{
this.pipes = middlewares;
return this;
}
then(finalCb)
{
let pipeline = this.pipes.reduce(this.carry() , this.prepareCb(finalCb));
pipeline(this.passable);
}
prepareCb(finalCb)
{
return function(passable)
{
finalCb(passable);
}
}
carry()
{
let that = this;
return function(stack , pipe)
{
return function(passable)
{
pipe.handle(passable , stack);
}
}
}
}
let request = {name:'Franklin Roosevelt', 'password': '32 President of USA'};
let pipeline = new Pipeline();
pipeline.send(request)
.through(middlewares)
.then(function(passable) { console.log("====JOB IS DONE===== =)"); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment