-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
77 lines (63 loc) · 2.17 KB
/
server.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
// /////////////////////////////////////////////////////////////////////////////
// IMPORTANT:
// THIS FILE IS READ ONLY, DO NOT MODIFY IT IN ANY WAY AS THAT WILL RESULT IN A TEST FAILURE
// /////////////////////////////////////////////////////////////////////////////
const http = require("http");
const fs = require("fs").promises;
const url = require("url");
const filePath = process.argv[2];
let config = null;
function requestsHandler(req, res) {
const requestUrl = url.parse(req.url, true);
const endpoint = config.api.find(
(api) => api.path === requestUrl.pathname && (api.method === req.method || req.method === 'OPTIONS')
);
// endpoint not found
if (!endpoint) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
return;
}
// handle cors
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', `OPTIONS, ${endpoint.method}`);
res.setHeader('Access-Control-Allow-Headers', '*');
res.setHeader('Access-Control-Max-Age', 3600);
if(req.method === 'OPTIONS'){
res.writeHead(200);
res.end();
return;
}
// endpoint requires authorization
if (
endpoint.authorization &&
req.headers.authorization !== `Bearer ${endpoint.authorization.token}`
) {
res.writeHead(endpoint.authorization.status, {
"Content-Type": "application/json",
});
res.end(JSON.stringify(endpoint.authorization.unauthorized));
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(endpoint.response));
}
async function main() {
try {
config = await fs.readFile(filePath, "utf8");
} catch (err) {
console.error("Error reading config file:", err);
return;
}
try {
config = JSON.parse(config);
} catch (err) {
console.error("Error parsing config file:", err);
return;
}
const server = http.createServer(requestsHandler);
server.listen(config.port, config.host, () =>
console.log(`Server running at http://${config.host}:${config.port}/`)
);
}
main();