Created
September 26, 2018 17:04
-
-
Save PlasmaPower/1f0670e88911cac546dc80548bca1865 to your computer and use it in GitHub Desktop.
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
const compose = require('koa-compose'); | |
const sleep = require('sleep-promise'); | |
/** | |
* Simple App Structure. | |
*/ | |
class App { | |
constructor () { | |
this.middleware = []; | |
} | |
use (fn) { | |
if (typeof fn !== 'function') { | |
throw new TypeError('middleware must be a function!'); | |
} | |
this.middleware.push(fn); | |
return this; | |
} | |
route (handler) { | |
let fn = compose(this.middleware); | |
return fn(this).then( () => this.handleRequest(handler) ); | |
} | |
handleRequest (handler) { | |
return handler(); | |
} | |
} | |
let app = new App(); | |
/** | |
* Setup Middleware | |
*/ | |
app.use( (ctx, next) => { | |
console.log("Middleware #1: Triggered"); | |
console.log("Middleware #1: Next"); | |
return next(); | |
}); | |
app.use( (ctx, next) => { | |
console.log("Middleware #2: Triggered"); | |
console.log("Middleware #2: Next"); | |
return next(); | |
}); | |
app.use( (ctx, next) => { | |
console.log("Middleware #3: Triggered"); | |
return sleep(2000).then( () => { | |
console.log("Middleware #3: Next"); | |
return next(); | |
}); | |
}); | |
app.route(() => console.log("Finished") ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment