Skip to content

Instantly share code, notes, and snippets.

@danielgormly
Last active March 19, 2017 06:43
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 danielgormly/ef05053d73c163e528ce151d3f3284bf to your computer and use it in GitHub Desktop.
Save danielgormly/ef05053d73c163e528ce151d3f3284bf to your computer and use it in GitHub Desktop.
Microcosm of Koa's flow control
/*
MiniKoa ^.^
- In the real Koa, the module Koa-composer takes on the recursive behaviour.
- This still works with async functions because await will automatically convert resolved values into promises.
- The most notable difference of course is that this doesn't respond to an http request instead it just runs instantly with whatever context object you give it.
*/
class MiniKoa {
constructor() {
this.middleware = [];
}
callback (ctx, index = 0) {
const isLast = index === this.middleware.length - 1;
let next = isLast ? () => {} : this.callback.bind(this, ctx, index + 1);
return this.middleware[index](ctx, next);
}
use(func) {
if(typeof func === 'function') this.middleware.push(func);
else throw new TypeError("Middleware must be of type Function");
}
}
const app = new MiniKoa();
app.use(async function(ctx, next) {
console.log(`${ctx.downstream} #1`);
await next();
console.log(`${ctx.upstream} #1`);
});
app.use(async function(ctx, next) {
console.log(`${ctx.downstream} #2`);
await next();
console.log(`${ctx.upstream} #2`);
});
app.use(async function(ctx, next) {
console.log(`${ctx.downstream} #3`);
await next();
console.log(`${ctx.upstream} #3`);
});
app.callback({upstream: 'upstream', downstream: 'downstream'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment