-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpapi.js
72 lines (54 loc) · 1.71 KB
/
httpapi.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
/*
* author: chengf
* just like koa middleware
* support async model
*/
const http = require('http');
module.exports = class HttpAPI {
constructor() {
this.middlewares = [];
}
static create() {
if (HttpAPI.instance) return HttpAPI.instance;
return new HttpAPI();
}
// action: (ctx:object,next:function)=>{};
use(action) {
if (typeof action !== 'function') return;
this.middlewares.push(action);
}
initMiddlewares(ctx) {
// if (this.middlewaresHttp) return;
this.middlewaresHttp = [];
const self = this;
if (!self.middlewares.length) return;
for (let i = self.middlewares.length - 1; i >= 0; i--) {
this.middlewaresHttp[i] = {
action: self.middlewares[i],
next: self.middlewares.length - 1 === i
? function () {
}
: self.middlewaresHttp[i + 1].action.bind(null, ctx, self.middlewaresHttp[i + 1].next)
}
}
}
async start(ctx) {
if (!this.middlewaresHttp.length) {
return;
}
await this.middlewaresHttp[0].action(ctx, this.middlewaresHttp[0].next);
}
listen(...params) {
const server = http.createServer(async (req, res) => {
const ctx = {
request: req,
response: res
};
ctx.response.setHeader('Content-Type', 'text/html; charset=utf-8');
this.initMiddlewares(ctx);
await this.start(ctx);
ctx.response.end();
});
server.listen(...params);
}
}