Skip to content

Instantly share code, notes, and snippets.

@flovilmart
Created September 8, 2020 01:17
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 flovilmart/cab4cd733f38bbeaff4043604449e666 to your computer and use it in GitHub Desktop.
Save flovilmart/cab4cd733f38bbeaff4043604449e666 to your computer and use it in GitHub Desktop.
frmwrk.js
// 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 };
})
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