Last active
August 3, 2023 19:18
-
-
Save hartzis/ce191533d8579afe2481ddd5e2c6024a to your computer and use it in GitHub Desktop.
Restify proxy pattern using http-proxy. Uses restify server.pre() to setup a pattern to handle proxy requests before all middleware.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* "restify": "^7.2.0", | |
* "http-proxy": "^1.17.0", | |
* | |
* The restify server will proxy requests that match keys in a `proxies` config. | |
* | |
*/ | |
const restify = require('restify'); | |
const httpProxy = require('http-proxy'); | |
const proxiesConfig = { | |
'/proxy': { | |
url: 'http://www.proxiedService.com', | |
whitelist: { | |
GET: '/api/v1/users/' | |
} | |
} | |
}; | |
/** | |
* Every key in proxies becomes a proxy path on the server | |
* ie. `/proxy` key becomes a path on the server - '/proxy' | |
*/ | |
function setupProxies(proxies = {}) { | |
// Setup proxy server if we have proxies | |
const httpProxyServer = Object.keys(proxies).length > 0 | |
? httpProxy.createProxyServer({}) | |
: undefined; | |
return function proxiesMiddleware(req, res, next) { | |
if (httpProxyServer === undefined) { | |
return next(); | |
} | |
const proxy = `/${req.url.split('/')[1]}`; | |
if ( | |
(proxy in proxies) && | |
proxies[proxy].whitelist && | |
proxies[proxy].whitelist[method] && | |
Array.isArray(proxies[proxy].whitelist[method]) && | |
proxies[proxy].whitelist[method] | |
.some(path => req.url.startsWith(`${proxy}${path}`)) | |
) { | |
req.url = req.url.substring(proxy.length); | |
// complete the actual proxy'ing of the request | |
httpProxyServer.web(req, res, { | |
target: proxies[proxy].url, | |
}); | |
} else { | |
next(); | |
} | |
}; | |
}; | |
const server = restify.createServer({ | |
name: 'proxy-test', | |
}); | |
/* | |
* Using server.pre() because it runs before all middleware. | |
* http://restify.com/docs/server-api/#pre | |
*/ | |
server.pre(setupProxies(proxiesConfig)); | |
const port = process.env.PORT || 3000; | |
server.listen(port); | |
console.log(`Server is listening on port ${port}`); | |
//..... | |
/* | |
* After starting the server you should be able to request to your proxy. | |
* | |
* $ curl http://localhost:3000/proxy/api/v1/users/1234 | |
* Would proxy to - http://www.proxiedService.com/api/v1/users/1234 | |
* | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, do you maybe have an example of this in dockerized environment?