-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpapi.js
138 lines (128 loc) · 4.21 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
const http = require("http");
const url = require("url");
class HttpApiServer{
constructor(apiEndpoints, {servername, logger, maxPostBodySize, bindAddress, port, handlerPreCall, enableLog, disableRootRes}, httpServerInstance){
if(typeof(apiEndpoints) != "object")
throw new TypeError("apiEndpoints must be an object");
this.apiEndpoints = apiEndpoints;
this.servername = servername || "?";
this.servername += " omz-js-lib/httpapi/1.2";
this.logger = logger || null;
this.maxPostBodySize = maxPostBodySize || 0x100000;
this.bindAddress = bindAddress || "::";
this.port = port || 80;
this.handlerPreCall = handlerPreCall || null;
this.enableLog = enableLog || false;
this.disableRootRes = disableRootRes || false;
if(!httpServerInstance){
httpServerInstance = http.createServer();
httpServerInstance.on("error", (e) => {
this.logger && this.logger.fatal("Server error: " + (e && e.stack || e));
});
httpServerInstance.listen({host: this.bindAddress, port: this.port}, () => {
this.logger && this.logger.info("Listening on " + this.bindAddress + ":" + this.port);
});
}
httpServerInstance.on("request", this.http_req.bind(this));
this.httpServerInstance = httpServerInstance;
}
http_req(req, res){
if(this.enableLog){
this.logger && this.logger.info(((req.headers["x-forwarded-for"] && req.headers["x-forwarded-for"].split(", ")[0]) || (req.connection.remoteAddress + ":" + req.connection.remotePort)) +
" - '" + req.method + " " + req.url + " HTTP/" + req.httpVersion + "'");
}
let surl = url.parse(req.url, true);
let endpoint = surl.pathname.substring(1);
let handler = this.apiEndpoints[endpoint];
if(surl.pathname == "/" && !this.disableRootRes){
this.http_respond(res, 403, {err: "Forbidden", "SERVER_IDENTIFICATION": this.servername});
}else if(handler){
const callHandler = async (...args) => {
try{
const h_this = {
respond: (status, json) => {
this.http_respond(res, status, json);
}
};
let additionalArgs = [];
if(this.handlerPreCall){
let aa = await Promise.resolve(this.handlerPreCall.call(h_this, req, res, surl, handler));
if(res.writableEnded)
return;
if(Array.isArray(aa))
additionalArgs = aa;
}
let err = await handler.call(h_this, ...args, ...additionalArgs);
if(!res.writableEnded){
if(err && Array.isArray(err))
this.http_respond(res, err[0] || 500, {err: err[1] || "(no message)", softerr: true});
else
this.http_respond(res, 204);
}
}catch(e){
this.logger && this.logger.error("Error while running api endpoint '" + endpoint + "': " + (e && e.stack || e));
this.http_respond(res, 500, {err: "Internal error"});
}
};
if(handler.length > 3 && this.maxPostBodySize > 0){ // 4th argument: postBody
if(req.method != "POST"){
this.http_respond(res, 405, {err: "POST is required"});
return;
}
let dataArray = [];
let datalen = 0;
req.on("data", (d) => {
datalen += d.length;
if(datalen > this.maxPostBodySize){
dataArray = false;
req.destroy();
return;
}
dataArray.push(d);
});
req.on("end", () => {
if(dataArray === false)
return;
callHandler(req, res, surl, Buffer.concat(dataArray));
});
}else{
callHandler(req, res, surl);
}
}else
this.http_respond(res, 404, {err: "Invalid endpoint"});
}
http_respond(res, status, json){
if(res.writableEnded)
return;
if(json){
if(json.err){
json.errmsg = json.err;
json.err = {
400: "BadRequest",
404: "NotFound",
405: "MethodNotAllowed",
500: "ServerError"
}[status] || "Error";
}
let data = Buffer.from(JSON.stringify(json));
res.writeHead(status, this.http_getHeaders({"content-length": data.length}));
res.end(data);
}else{
res.writeHead(status, this.http_getHeaders({"content-length": 0}));
res.end();
}
}
http_getHeaders(additional){
let headers = {"server": this.servername, "content-type": "application/json"};
if(typeof(additional) == "object"){
for(let a in additional){
headers[a] = additional[a];
}
}
return headers;
}
close(){
this.httpServerInstance.close();
}
}
module.exports = {HttpApiServer};