-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
78 lines (66 loc) · 1.5 KB
/
index.ts
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
/**
* @author afu
* @license MIT
*/
import IWebApplication from './web/IWebApplication';
import http = require('http');
import Hook = require('./core/Hook');
/**
* 入口
*/
class CandyJs {
/**
* http server
*/
public server: http.Server = null;
/**
* 当前应用
*/
public app: IWebApplication;
constructor(application: any) {
this.app = application;
}
// web
private requestListener(req: any, res: any): void {
try {
this.app.requestListener(req, res);
} catch(e) {
this.app.handlerException(e, res);
}
}
// handler
private handler(req: any, res: any): void {
new Hook().trigger(req, res, (request, response) => {
this.requestListener(request, response);
});
}
/**
* 获取 http server
*
* @return {http.Server}
*/
public getServer(): http.Server {
return http.createServer((req, res) => {
this.handler(req, res);
});
}
/**
* listen
*
* If you want to create HTTPS server you can do so as shown here
*
* ```
* const https = require('https');
* const CandyJs = require('candyjs');
*
* const main = new CandyJs({ ... });
* https.createServer({ ... }, main.handler.bind(main)).listen(443);
* ```
*
*/
public listen(...args): void {
this.server = this.getServer();
this.server.listen(...args);
}
}
export = CandyJs;