Skip to content

Commit

Permalink
PharmaLedger-IMI/epi-workspace#867 - added new middleware (forwardReq…
Browse files Browse the repository at this point in the history
…uest) which handles

url /forwardRequestForAuthenticatedClient
  • Loading branch information
asaccool committed Aug 11, 2022
1 parent 652139e commit 500a9c1
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 1 deletion.
41 changes: 41 additions & 0 deletions components/requestForwarder/index.js
Original file line number Diff line number Diff line change
@@ -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();
});
}
3 changes: 3 additions & 0 deletions config/default.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ const defaultConfig = {
},
"stream": {
"module": "./components/stream"
},
"requestForwarder":{
"module": "./components/requestForwarder"
}
},
"tokenBucket": {
Expand Down
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
})();

Expand Down
3 changes: 2 additions & 1 deletion utils/middlewares/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 500a9c1

Please # to comment.