Created
September 12, 2019 12:18
-
-
Save madrussa/094e7ea0be033f06894a9ac8217462f7 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
This file contains hidden or 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
'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