-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·100 lines (78 loc) · 2.21 KB
/
index.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
const http = require("http");
const servers = require("./servers");
const mapServers = new Map();
for (const server of servers) {
const { port, name, notFound } = server;
if (!port || port < 80) {
continue;
}
const isServer = mapServers.get(port);
if (isServer) {
continue;
}
mapServers.set(port, true);
const { status: statusNotFound, body: bodyNotFound } = notFound;
const { paths: pathsConfig } = server;
const paths = new Map();
for (const value of pathsConfig) {
const { path, methods } = value;
const httpMethod = new Map();
for (const mvalues of methods) {
const { method, response } = mvalues;
httpMethod.set(method, response);
}
paths.set(path, httpMethod);
}
const httpServer = http.createServer((req, res) => {
const { url, method, headers } = req;
const log = {
serverName: name,
url,
method,
headers,
};
console.log(log);
if (method === "OPTIONS") {
res.statusCode = 200;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Credentials", "true");
res.setHeader("Access-Control-Allow-Headers", "*");
res.end();
return;
}
const path = paths.get(url);
if (!path) {
res.statusCode = statusNotFound;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(bodyNotFound));
return;
}
const response = path.get(method.toLocaleLowerCase());
if (!response) {
res.statusCode = statusNotFound;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(bodyNotFound));
return;
}
const { status, body, headers: responseHeaders } = response;
statusCode = status;
res.statusCode = statusCode;
if (!responseHeaders) {
res.setHeader("Content-Type", "application/json");
} else {
for (const [key, value] of Object.entries(responseHeaders)) {
res.setHeader(key, value);
}
}
res.end(JSON.stringify(body));
});
mapServers.clear();
httpServer.listen(port, () => {
const listen = {
name,
port,
};
console.log(listen);
});
}