-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.js
101 lines (85 loc) · 2.39 KB
/
http.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import http from 'http';
import https from 'https';
import express from 'express';
import bodyParser from 'body-parser';
import config, { sslConfig } from '../config';
import { HTTP_STATUS_CODES } from '../vars';
class HttpServerCore {
constructor() {
this.server = null;
this.app = null;
this.socketClientsNotifier = () => console.error('Method not attached!');
}
initConnectionWithQ2A(middlewareList) {
this.app = express();
this.app.use(bodyParser.json());
if (!Array.isArray(middlewareList) || middlewareList.length === 0) {
throw TypeError('middlewareList argument must be non empty array!');
}
middlewareList.forEach(({ method, path, listener }) => {
if (!method || !path || !listener) {
throw ReferenceError(`
middleware must contain: method, path and listener params!
Received method: "${method}", path: "${path}", listener: "${listener}"
`);
}
this.app[method](path, listener);
});
}
initServerForWebSocket() {
this.server = this.createHttpServerWithOptionalCert();
this.server.listen(config.port.http, () =>
console.log(`Server is listening on port ${config.port.http}, over ${config.protocol.toUpperCase()} protocol.`)
);
}
createHttpServerWithOptionalCert() {
if (config.protocol === 'https') {
return https.createServer(
{
key: sslConfig.key,
cert: sslConfig.cert,
},
this.app
);
}
return http.createServer(this.app);
}
attachSocketClientsNotifier(fn) {
this.socketClientsNotifier = fn;
}
}
class HttpServer extends HttpServerCore {
constructor() {
super();
this.initConnectionWithQ2A([
{
method: 'all',
path: '*',
listener: HttpServer.onAll,
},
{
method: 'post',
path: '/',
listener: this.onPost.bind(this),
},
]);
this.initServerForWebSocket();
}
static onAll(req, res, next) {
if (req.headers.token !== config.token) {
res.sendStatus(HTTP_STATUS_CODES.FORBIDDEN);
return;
}
if (req.method !== 'POST') {
res.sendStatus(HTTP_STATUS_CODES.METHOD_NOT_ALLOWED);
return;
}
next();
}
onPost(req, res) {
console.log('(onPost) rq.body:', req.body);
res.sendStatus(HTTP_STATUS_CODES.OK);
this.socketClientsNotifier(req.body.action);
}
}
export default HttpServer;