git ssb

1+

dinoworm ๐Ÿ› / catstack



Tree: 1b77a91b5043f96c866edfed9022577b95e3c14f

Files: 1b77a91b5043f96c866edfed9022577b95e3c14f / app / proxy.js

1725 bytesRaw
1const http = require('http')
2const httpProxy = require('http-proxy')
3const Url = require('url')
4const startsWith = require('lodash').startsWith
5const assign = require('lodash').assign
6const redirect = require('predirect')
7
8module.exports = { createServer }
9
10function 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
48function 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
57function targetPath (service, pathname) {
58 return pathname.slice(service.url.pathname.length - 1)
59}
60
61function matches (service, pathname) {
62 return startsWith(pathname, service.url.pathname)
63}
64

Built with git-ssb-web