Files: ed26f7c5c655a65d700ecac4cddac76d22aad40a / app / proxy.js
1181 bytesRaw
1 | const http = require('http') |
2 | const httpProxy = require('http-proxy') |
3 | const Url = require('url') |
4 | const startsWith = require('lodash').startsWith |
5 | const assign = require('lodash').assign |
6 | |
7 | module.exports = { createServer } |
8 | |
9 | function createServer (config) { |
10 | const proxy = httpProxy.createProxyServer({ |
11 | ignorePath: true |
12 | }) |
13 | |
14 | const server = http.createServer(function (req, res) { |
15 | const url = Url.parse(req.url) |
16 | |
17 | if (matches(config.api, url.pathname)) { |
18 | proxy.web(req, res, { target: targetUrl(config.api, url.pathname) }) |
19 | } else if (matches(config.static, url.pathname)) { |
20 | proxy.web(req, res, { target: targetUrl(config.static, url.pathname) }) |
21 | } else { |
22 | proxy.web(req, res, { target: targetUrl(config.render, url.pathname) }) |
23 | } |
24 | }) |
25 | |
26 | return server |
27 | } |
28 | |
29 | function targetUrl (service, pathname) { |
30 | const url = assign( |
31 | {}, service.url, |
32 | { port: service.port }, |
33 | { pathname: targetPath(service, pathname) } |
34 | ) |
35 | return Url.format(url) |
36 | } |
37 | |
38 | function targetPath (service, pathname) { |
39 | return pathname.slice(service.url.pathname.length - 1) |
40 | } |
41 | |
42 | function matches (service, pathname) { |
43 | return startsWith(pathname, service.url.pathname) |
44 | } |
45 |
Built with git-ssb-web