-
Notifications
You must be signed in to change notification settings - Fork 43
/
like-koa2.js
58 lines (49 loc) · 1.01 KB
/
like-koa2.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
51
52
53
54
55
56
57
58
const http = require("http");
// 组合中间件
function compose(middlewareList) {
return function (ctx) {
function dispatch(i) {
const fn = middlewareList[i];
try {
return Promise.resolve(
fn(ctx, dispatch.bind(null, i + 1)) // promise
);
} catch (err) {
return Promise.reject(err);
}
}
return dispatch(0);
};
}
class LikeKoa2 {
constructor() {
this.middlewareList = [];
}
use(fn) {
this.middlewareList.push(fn);
return this;
}
createContext(req, res) {
const ctx = {
req,
res,
};
ctx.query = req.query;
return ctx;
}
handleRequest(ctx, fn) {
return fn(ctx);
}
callback() {
const fn = compose(this.middlewareList);
return (req, res) => {
const ctx = this.createContext(req, res);
return this.handleRequest(ctx, fn);
};
}
listen(...args) {
const server = http.createServer(this.callback());
server.listen(...args);
}
}
module.exports = LikeKoa2;