UNPKG

1.32 kBJavaScriptView Raw
1import R from "ramda";
2import httpProxy from "http-proxy"; // See: https://github.com/nodejitsu/node-http-proxy
3import { sortAppsByRoute } from "./util";
4import log from "./log";
5
6
7const proxy = httpProxy.createProxyServer();
8proxy.on("error", (err) => {
9 switch (err.code) {
10 case "ECONNRESET":
11 // Ignore this error:
12 // It is a bug in the `node-http-proxy` that is getting fixed.
13 // See issue: https://github.com/nodejitsu/node-http-proxy/issues/898
14 break;
15 default: log.error(`PROXY error:`, err);
16 }
17});
18
19
20
21
22
23export 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 // An app matches the current route.
35 // Proxy the request to it.
36 const target = { host: "localhost", port: app.port };
37 // log.info(`Route: ${ req.path } => port:${ app.port }`);
38 proxy.web(req, res, { target });
39 } else {
40 // No matching route.
41 res.status(404).send({ message: "Route not found", domain, path });
42 }
43 });
44};