Skip to content

Instantly share code, notes, and snippets.

@bioshazard
Created August 31, 2023 15:32
Show Gist options
  • Save bioshazard/3cb12bfa2b83792cba9a197f5e85afdb to your computer and use it in GitHub Desktop.
Save bioshazard/3cb12bfa2b83792cba9a197f5e85afdb to your computer and use it in GitHub Desktop.
import https from 'https';
import request from 'request';
import fs from 'fs';
import bodyParser from 'body-parser';
var jsonParser = bodyParser()
const backend = {
'proto': 'https',
'host': 'your-instance-name.openai.azure.com'
}
// should match the https host you are planning to connect with
const sslOptions = {
key: fs.readFileSync(process.env["CERTIFICATE_KEY"]),
cert: fs.readFileSync(process.env["CERTIFICATE_CRT"]),
};
const server = https.createServer(sslOptions, (req, res) => {
const url = backend["proto"] + '://' + backend["host"] + req.url;
const headers = {
...req.headers,
host: backend["host"]
}
const options = {
url,
headers,
method: req.method,
};
if(req.method === 'POST') {
console.log("POST CAUGHT")
jsonParser(req, res, (error) => {
console.log(req.body)
options["body"] = JSON.stringify(req.body)
relayRequest(req, res, options, req.body)
})
} else {
relayRequest(req, res, options)
}
});
function relayRequest(req, res, options, body) {
console.log("\n\n\n# Options\n\n\n")
console.log(options["url"])
console.log(req.method)
console.log(req.body)
console.log(req)
request(options)
.on('error', (error) => {
res.statusCode = 500;
res.end('Error occurred while relaying request to the backend');
console.log(error)
})
.on("complete", (resp, body) => {
console.log("\n\n# RESPONSE\n\n")
console.log(resp.toJSON())
})
.pipe(res); // this is the trick, pipe is directly...
}
// Start the server
const port = 44351; // Replace with your desired port number
server.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment