Skip to content

Instantly share code, notes, and snippets.

@PlasmaPower
Created September 26, 2018 17:04
Show Gist options
  • Save PlasmaPower/1f0670e88911cac546dc80548bca1865 to your computer and use it in GitHub Desktop.
Save PlasmaPower/1f0670e88911cac546dc80548bca1865 to your computer and use it in GitHub Desktop.
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