Last active
November 6, 2017 23:08
-
-
Save anotherxx/bb641b131d58973c0c938358f778c5bb to your computer and use it in GitHub Desktop.
Middleware js Laravel like implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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