-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.js
83 lines (73 loc) · 1.83 KB
/
application.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const http = require('http')
let request = {
get url () {
return this.req.url
}
}
let response = {
get body () {
return this._body
},
set body (value) {
this._body = value
}
}
let context = {
get url () {
return this.request.url
},
get body () {
return this.response.body
},
set body (value) {
this.response.body = value
}
}
class Application {
constructor () {
// this.callBack = () => {}
this.context = context
this.request = request
this.response = response
this.middlewares = []
}
// 定义一个use
use (callback) {
this.middlewares.push(callback)
// this.callback = callback
}
compose (middlewares) {
return function (context) {
return dispatch(0)
function dispatch(i) {
let fn = middlewares[i]
if (!fn) {
return Promise.resolve()
}
return Promise.resolve(fn(context, function next() {
return dispatch(i + 1)
}))
}
}
}
listen (...args) {
const server = http.createServer(async (req, res) => {
let ctx = this.createCtx(req, res)
const fn = this.compose(this.middlewares)
await fn(ctx)
// await this.callBack(ctx)
ctx.res.end(ctx.body)
// this.callBack(req, res)
})
server.listen(...args)
}
createCtx (req, res) {
let ctx = Object.create(this.context)
ctx.request = Object.create(this.request)
ctx.response = Object.create(this.response)
ctx.req = ctx.request.req = req
ctx.res = ctx.response.res = res
return ctx
}
}
module.exports = Application