1 | import R from "ramda";
|
2 | import httpProxy from "http-proxy";
|
3 | import { sortAppsByRoute } from "./util";
|
4 | import log from "./log";
|
5 |
|
6 |
|
7 | const proxy = httpProxy.createProxyServer();
|
8 | proxy.on("error", (err) => {
|
9 | switch (err.code) {
|
10 | case "ECONNRESET":
|
11 |
|
12 |
|
13 |
|
14 | break;
|
15 | default: log.error(`PROXY error:`, err);
|
16 | }
|
17 | });
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | export default (apps, middleware) => {
|
24 | apps = sortAppsByRoute(apps);
|
25 | const findMatchingApp = (domain, path) => {
|
26 | return R.find(app => app.route.match(domain, path), apps);
|
27 | };
|
28 |
|
29 | middleware.get("*", (req, res) => {
|
30 | const domain = req.get("host").split(":")[0];
|
31 | const path = req.url;
|
32 | const app = findMatchingApp(domain, path);
|
33 | if (app) {
|
34 |
|
35 |
|
36 | const target = { host: "localhost", port: app.port };
|
37 |
|
38 | proxy.web(req, res, { target });
|
39 | } else {
|
40 |
|
41 | res.status(404).send({ message: "Route not found", domain, path });
|
42 | }
|
43 | });
|
44 | };
|