diff --git a/components/requestForwarder/index.js b/components/requestForwarder/index.js new file mode 100644 index 0000000..718012e --- /dev/null +++ b/components/requestForwarder/index.js @@ -0,0 +1,41 @@ +const registeredUrl = "/forwardRequestForAuthenticatedClient"; + +module.exports = function(server){ + server.post(registeredUrl, require("./../../utils/middlewares/index").requestBodyJSONMiddleware); + + server.post(registeredUrl, function(req, res, next){ + let url = req.body.url; + + if(!url){ + res.statusCode = 400; + return res.end(); + } + + let body = req.body.body || ""; + let options = req.body.options || {method: "POST"}; + + let http = require("http"); + if(url.startsWith("https://")){ + http = require("https"); + } + + console.log(`Forwarding request ${options.method} to url ${url}`); + + let request = http.request(url, options, (response)=>{ + res.statusCode = response.statusCode; + if(res.statusCode > 300){ + res.end(); + } + response.on("data", res.write); + res.on('end', res.end); + }); + + request.on("error", (err)=>{ + res.statusCode = 500; + res.end(); + }); + + request.write(body); + request.end(); + }); +} \ No newline at end of file diff --git a/config/default.js b/config/default.js index c1dac5e..82cd045 100644 --- a/config/default.js +++ b/config/default.js @@ -92,6 +92,9 @@ const defaultConfig = { }, "stream": { "module": "./components/stream" + }, + "requestForwarder":{ + "module": "./components/requestForwarder" } }, "tokenBucket": { diff --git a/index.js b/index.js index 0ecda00..9322f99 100644 --- a/index.js +++ b/index.js @@ -28,6 +28,7 @@ const CHECK_FOR_RESTART_COMMAND_FILE_INTERVAL = 500; require('./components/secrets'); require('./components/cloudWallet'); require('./components/stream'); + require('./components/requestForwarder'); //end })(); diff --git a/utils/middlewares/index.js b/utils/middlewares/index.js index 2bdd734..0cc690a 100644 --- a/utils/middlewares/index.js +++ b/utils/middlewares/index.js @@ -23,7 +23,8 @@ function requestBodyJSONMiddleware(request, response, next) { try { body = JSON.parse(data); } catch (e) { - return response.send(500, 'Unable to decode JSON request body') + response.statusCode = 500; + return response.end("Unable to decode JSON request body"); } request.body = body; next();