Created
September 8, 2020 01:17
-
-
Save flovilmart/cab4cd733f38bbeaff4043604449e666 to your computer and use it in GitHub Desktop.
frmwrk.js
This file contains 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
// Makes a sync middleware | |
const make = (name) => { | |
return (ctx, next) => { | |
ctx.calls = ctx.calls || 0 | |
ctx.calls += 1; | |
console.log(`Doing ${name} PRE`); | |
return next(ctx); | |
} | |
} | |
// makes an async middleware | |
const makeAsync = (name) => { | |
return async (ctx, next) => { | |
console.log(`Doing ${name} PRE`); | |
const r = await next(ctx); | |
console.log(`Doing ${name} POST`, r); | |
return { ...r, name }; | |
} | |
} | |
// Processes a handler with middlewares, in an out | |
function use(middlewares, handler, ctx = {}) { | |
const [m, ...rest] = middlewares; | |
if (!m) { | |
return handler(ctx); | |
} | |
return m(ctx, (uCtx) => { | |
return use(rest, handler, uCtx || ctx); | |
}); | |
} | |
// Make 4 middlewares | |
const a = make('1'); | |
const b = makeAsync('2'); | |
const c = make('3'); | |
const d = makeAsync('4'); | |
use([ | |
a, b, c, d | |
], async (ctx) => { | |
console.log('Doing route... '); | |
return { a: 1, b: 2, calls: ctx.calls }; | |
}) |
This file contains 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
Doing 1 PRE | |
Doing 2 PRE | |
Doing 3 PRE | |
Doing 4 PRE | |
Doing route... | |
Doing 4 POST { a: 1, b: 2, calls: 2 } | |
Doing 2 POST { a: 1, b: 2, calls: 2, name: '4' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment