Last active
March 19, 2017 06:43
-
-
Save danielgormly/ef05053d73c163e528ce151d3f3284bf to your computer and use it in GitHub Desktop.
Microcosm of Koa's flow control
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
/* | |
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