Skip to content

Instantly share code, notes, and snippets.

@gauravds
Forked from madrussa/ProxyController.js
Created April 10, 2023 19:41
Show Gist options
  • Save gauravds/f3cb55f402625de3d4517a7d51e9dae3 to your computer and use it in GitHub Desktop.
Save gauravds/f3cb55f402625de3d4517a7d51e9dae3 to your computer and use it in GitHub Desktop.
Using node-http-proxy in AdonisJs as a controller action, allows Adonis to act as a gateway
'use strict'
const httpProxy = require('http-proxy');
const Logger = use('Logger');
class ProxyController {
/**
* Proxy any request to the targeted PROXY_HOST
*
* @param {import('@adonisjs/framework/src/Request')} request
* @param {import('@adonisjs/framework/src/Response')} response
* @return {Promise}
*/
async proxy ({ request, response }) {
Logger.info('requested url: %s', request.url());
const proxy = httpProxy.createProxyServer();
// Create proxy promise, so we can await the body of the proxy response
const prom = new Promise((resolve, reject) => {
Logger.info('Creating proxy promise for %s', request.url());
// Setup request listener, resolve body to return
proxy.on('proxyRes', (proxyRes, req, res) => {
let body = [];
proxyRes.on('data', function (chunk) {
body.push(chunk);
});
proxyRes.on('end', function () {
body = Buffer.concat(body).toString();
resolve(body);
});
});
// Forward the post body, do not mutate the body as request headers will be wrong
// and cannot be set here
if (['POST', 'PUT', 'post', 'put'].includes(request.method())) {
request.request.body = request.raw();
proxy.on('proxyReq', (proxyReq, req, res, options) => {
if (req.body) {
proxyReq.write(req.body);
}
});
}
// Proxy the request, remember to use native request and response objects
proxy.web(request.request, response.response, {
target: process.env.PROXY_HOST,
}, (e) => {
Logger.info('Proxy error', e);
reject(e);
});
});
const result = await prom;
response.send(result);
return response;
}
}
module.exports = ProxyController;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment