-
Notifications
You must be signed in to change notification settings - Fork 1
/
moa.js
56 lines (48 loc) · 1.15 KB
/
moa.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
const http = require('http')
const context = require('./context')
const request = require('./request')
const response = require('./response')
class Moa {
constructor() {
this.middlewares = []
}
use(middleware) {
this.middlewares.push(middleware)
}
listen(...args) {
const server = http.createServer(async (req, res) => {
// 创建上下文
const ctx = this.createContext(req, res)
const fn = this.compose(this.middlewares)
await fn(ctx)
// 响应
res.end(ctx.body)
})
server.listen(...args)
}
createContext(req, res) {
const ctx = Object.create(context)
ctx.request = Object.create(request)
ctx.response = Object.create(response)
ctx.req = ctx.request.req = req
ctx.res = ctx.response.res = res
return ctx
}
compose(middlewares) {
return function (ctx) {
return dispatch(0)
function dispatch(i) {
let fn = middlewares[i]
if (!fn) {
return Promise.resolve()
}
return Promise.resolve(
fn(ctx, function () {
return dispatch(i + 1)
})
)
}
}
}
}
module.exports = Moa