Files: 8ff89763aa5a55ca923acb5f2228036e30440737 / app / proxy.js
1725 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 | const redirect = require('predirect') |
7 | |
8 | module.exports = { createServer } |
9 | |
10 | function createServer (config) { |
11 | const proxy = httpProxy.createProxyServer({ |
12 | ignorePath: true |
13 | }) |
14 | |
15 | proxy.on('error', function (err, req, res) { |
16 | console.log(JSON.stringify({ |
17 | name: 'proxy', |
18 | level: 'warn', |
19 | url: req.url, |
20 | message: err.message |
21 | })) |
22 | if (err.code === 'ECONNREFUSED') { |
23 | // HACK delay request for one second |
24 | setTimeout(function () { |
25 | redirect(req, res, `http://localhost:${config.proxy.port}${req.url}`) |
26 | }, 1000) |
27 | } else { |
28 | res.writeHead(500, { 'Content-Type': 'text/plain' }) |
29 | res.end('Internal Server Error') |
30 | } |
31 | }) |
32 | |
33 | const server = http.createServer(function (req, res) { |
34 | const url = Url.parse(req.url) |
35 | |
36 | if (matches(config.api, url.pathname)) { |
37 | proxy.web(req, res, { target: targetUrl(config.api, url.pathname) }) |
38 | } else if (matches(config.static, url.pathname)) { |
39 | proxy.web(req, res, { target: targetUrl(config.static, url.pathname) }) |
40 | } else { |
41 | proxy.web(req, res, { target: targetUrl(config.render, url.pathname) }) |
42 | } |
43 | }) |
44 | |
45 | return server |
46 | } |
47 | |
48 | function targetUrl (service, pathname) { |
49 | const url = assign( |
50 | {}, service.url, |
51 | { port: service.port }, |
52 | { pathname: targetPath(service, pathname) } |
53 | ) |
54 | return Url.format(url) |
55 | } |
56 | |
57 | function targetPath (service, pathname) { |
58 | return pathname.slice(service.url.pathname.length - 1) |
59 | } |
60 | |
61 | function matches (service, pathname) { |
62 | return startsWith(pathname, service.url.pathname) |
63 | } |
64 |
Built with git-ssb-web