-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (43 loc) · 1 KB
/
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
51
52
53
54
55
56
57
58
59
const http = require('http')
// 主类
class Application {
constructor() {
this.middleware = []
}
// 注册中间间
use(arg) {
this.middleware.push(arg)
}
listen(...arg) {
// 服务实例
const server = http.createServer(async (req, res) => {
// 上下文
let ctx = new Context(req, res)
ctx.body = '11'
// 注册洋葱
let fn = compose(this.middleware)
// 执行
await fn(ctx)
ctx.res.end(ctx.body)
})
// 开启服务
server.listen(...arg)
}
}
// req , res 合集上下文
class Context {
constructor(req, res) {
this.req = req
this.res = res
}
}
function compose(middleware) {
return (ctx) => {
// 洋葱执行模式
const dispatch = (i) => {
middleware[i] && middleware[i](ctx, () => dispatch(i + 1))
}
dispatch(0)
}
}
module.exports = Application