-
Notifications
You must be signed in to change notification settings - Fork 18
/
bridgeServer.js
115 lines (101 loc) · 2.56 KB
/
bridgeServer.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
'use strict';
import httpServer from "./httpServer";
class Request {
constructor(rawRequest) {
this.requestId = rawRequest.requestId;
this.postData = rawRequest.postData;
this.type = rawRequest.type;
this.url = rawRequest.url;
}
get data() {
return JSON.parse(this.postData);
}
}
class Response {
constructor(requestId) {
this.requestId = requestId;
this.closed = false;
}
send(code, type, body) {
if (this.closed) {
throw new Error('Response already sent');
}
httpServer.respond(this.requestId, code, type, body);
this.closed = true;
}
json(obj, code = 200) {
this.send(code, 'application/json', JSON.stringify(obj));
}
html(html, code = 200) {
return this.send(code, 'text/html', html);
}
}
class BridgeServer {
static server;
constructor(serviceName, devMode=false) {
if (!serviceName) {
throw new Error('Invalid service name');
}
if (BridgeServer.server) {
if (devMode) {
BridgeServer.server.stop();
} else {
throw new Error(
'Only one instance of HttpServer is allowed. Use HttpServer.server to access the instance.',
);
}
}
this.callbacks = [];
this.serviceName = serviceName;
BridgeServer.server = this;
}
get(url, callback) {
this.callbacks.push({method: 'GET', url, callback});
}
post(url, callback) {
this.callbacks.push({method: 'POST', url, callback});
}
put(url, callback) {
this.callbacks.push({method: 'PUT', url, callback});
}
delete(url, callback) {
this.callbacks.push({method: 'DELETE', url, callback});
}
patch(url, callback) {
this.callbacks.push({method: 'PATCH', url, callback});
}
use(callback) {
this.callbacks.push({method: '*', url: '*', callback});
}
listen(port) {
if (port < 0 || port > 65535) {
throw new Error('Invalid port number');
}
httpServer.start(port, this.serviceName, async rawRequest => {
const request = new Request(rawRequest);
const callbacks = this.callbacks.filter(
c =>
(c.method === request.type || c.method === '*') &&
(c.url === request.url || c.url === '*'),
);
for (const c of callbacks) {
const response = new Response(request.requestId);
const result = await c.callback(request, response);
if (result) {
response.json(result);
}
if (response.closed) {
return;
}
}
});
}
stop() {
httpServer.stop();
}
}
module.exports = {
BridgeServer,
Request,
Response,
};