-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsuper-mini-koa.js
More file actions
35 lines (35 loc) · 976 Bytes
/
Copy pathsuper-mini-koa.js
File metadata and controls
35 lines (35 loc) · 976 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const http = require('http');
module.exports = class SuperMiniKoa {
constructor() {
this.middleware = [];
}
use(fn) {
this.middleware.push(fn);
}
listen(...args) {
return http.createServer(this.callback.bind(this)).listen(...args);
}
callback(req, res) {
const fn = this.compose(this.middleware);
const handleError = e => { throw new Error(e); };
const handleResponse = () => { res.end(res.body); };
const ctx = { req, res, app: this, state: {} };
return fn(ctx).then(handleResponse).catch(handleError);
}
compose(middleware) {
return function(ctx) {
let index = -1;
const dispatch = i => {
index = i;
let fn = middleware[i];
if (i === middleware.length) return Promise.resolve();
try {
return Promise.resolve(fn(ctx, () => dispatch(i + 1)));
} catch (err) {
return Promise.reject(err);
}
}
return dispatch(0);
}
}
}