-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (46 loc) · 1008 Bytes
/
index.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const http = require("http");
const compose = require("./compose");
function Koa() {
if (!(this instanceof Koa)) {
return new Koa();
}
this.middlewares = [];
return this;
}
Koa.prototype = {
constructor: Koa,
respond: function(cxt) {
cxt.res.end(cxt.body);
},
handleContext: function(req, res) {
const cxt = {};
cxt.req = req;
cxt.res = res;
return cxt;
},
handleRequest: function(cxt, fn) {
return fn(cxt)
.then(() => {
return this.respond(cxt);
})
.catch(err => {
console.log(err);
});
},
callback: function() {
const fn = compose(this.middlewares);
return (req, res) => {
const cxt = this.handleContext(req, res);
return this.handleRequest(cxt, fn);
};
},
use: function(middleware) {
this.middlewares.push(middleware);
return this;
},
listen: function(...args) {
const app = http.createServer(this.callback());
app.listen(...args);
}
};
module.exports = Koa;