Created
January 22, 2021 10:43
-
-
Save truongluu/e55f746e6875994ed59c7826c0ee4032 to your computer and use it in GitHub Desktop.
illustrate handling middleware
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
| const context = { rq: {}, rp: {} }; | |
| const md1 = async ({ rq, rp }, next, args) => { | |
| console.log("md1 rq", rq); | |
| console.log("md1 next", next); | |
| rq.a = 1; | |
| console.log("md1 args", args); | |
| await next(); | |
| }; | |
| const md2 = async ({ rq, rp }, next, args) => { | |
| console.log("md2 rq", rq); | |
| console.log("md2 next", next); | |
| rq.b = 2; | |
| console.log("md2 args", args); | |
| await next(); | |
| }; | |
| const md3 = async ({ rq, rp }, next, args) => { | |
| console.log("md3 rq", rq); | |
| console.log("md3 next", next); | |
| rq.c = 4; | |
| console.log("md3 args", args); | |
| await next(); | |
| }; | |
| const mds = [md1, md2, md3]; | |
| (async function () { | |
| try { | |
| const mdsRS = mds.reverse(); | |
| mdsRS.forEach((middleWareHandler, index) => { | |
| if (!index) { | |
| mdsRS[index] = middleWareHandler.bind(null, context, (context) => {}); | |
| } else { | |
| mdsRS[index] = middleWareHandler.bind(null, context, mds[index - 1]); | |
| } | |
| }); | |
| // Call the first middleware | |
| if (mdsRS[mdsRS.length - 1]) { | |
| mdsRS[mdsRS.length - 1](); | |
| } | |
| console.log("context change after proccess middleware", context); | |
| // Process router | |
| // await routerHandler(context); | |
| } catch (err) { | |
| console.log("err", err); | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment