-
Notifications
You must be signed in to change notification settings - Fork 37
/
startServer
executable file
·77 lines (68 loc) · 2.26 KB
/
startServer
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
#!/usr/bin/env node
const { spawn } = require("child_process");
const http = require("http");
const httpProxy = require("http-proxy");
const services = [
{ route: "/billing/*", path: "services/billing-api", port: 3001 },
{ route: "/notes/*", path: "services/notes-api", port: 3002 }
];
// Start `sls offline` for each service
services.forEach(service => {
const child = spawn(
"sls",
["offline", "start", "--stage", "dev", "--port", service.port],
{ cwd: service.path }
);
child.stdout.setEncoding("utf8");
child.stdout.on("data", chunk => console.log(chunk));
child.stderr.on("data", chunk => console.log(chunk));
child.on("close", code => console.log(`child exited with code ${code}`));
});
// Start a proxy server on port 8080 forwarding based on url path
const proxy = httpProxy.createProxyServer({});
const server = http.createServer(function(req, res) {
const service = services.find(per => urlMatchRoute(req.url, per.route));
// Case 1: matching service FOUND => forward request to the service
if (service) {
proxy.web(req, res, { target: `http://localhost:${service.port}` });
}
// Case 2: matching service NOT found => display available routes
else {
res.writeHead(200, { "Content-Type": "text/plain" });
res.write(
`Url path "${req.url}" does not match routes defined in services\n\n`
);
res.write(`Available routes are:\n`);
services.map(service => res.write(`- ${service.route}\n`));
res.end();
}
});
server.listen(8080);
// Check match route
// - ie. url is '/notes/123'
// - ie. route is '/notes/*'
function urlMatchRoute(url, route) {
const urlParts = url.split("/");
const routeParts = route.split("/");
for (let i = 0, l = routeParts.length; i < l; i++) {
const urlPart = urlParts[i];
const routePart = routeParts[i];
// Case 1: If either part is undefined => not match
if (urlPart === undefined || routePart === undefined) {
return false;
}
// Case 2: If route part is match all => match
if (routePart === "*") {
return true;
}
// Case 3: Exact match => keep checking
if (urlPart === routePart) {
continue;
}
// Case 4: route part is variable => keep checking
if (routePart.startsWith("{")) {
continue;
}
}
return true;
}