Skip to content

Instantly share code, notes, and snippets.

@sullemanhossam
Created June 24, 2024 23:39
Show Gist options
  • Save sullemanhossam/8d1c830a4d4496f0aeb201e3df388965 to your computer and use it in GitHub Desktop.
Save sullemanhossam/8d1c830a4d4496f0aeb201e3df388965 to your computer and use it in GitHub Desktop.
const { logger } = require('./logger');
const fetch = require('node-fetch'); // Ensure you have node-fetch installed
/**======================
** URLBUILDER
*@param ports array of int
*@param path string
*@return object
*========================**/
class urlBuilder {
constructor(ports, path) {
this.ports = ports;
this.path = path.startsWith('/') ? path : '/' + path;
this.hosts = [
'localhost',
'192.168.239.16',
// Add more hosts as needed
];
}
async findFirstSuccessfulHost() {
logger({
level: 'info',
message: `Pinging hosts on ports ${this.ports.join(
', '
)} and logging the results.`,
});
for (let port of this.ports) {
for (let host of this.hosts) {
const url = `${host}:${port}${this.path}`;
try {
const response = await this.makeRequest(url);
if (response.ok) {
console.log(`Successful response from ${url}`);
return { host, port, path: this.path };
}
} catch (error) {
console.error(`Error requesting ${url}`, error);
}
}
}
console.log('No host returned a 200 status code.');
return null;
}
async makeRequest(url) {
try {
const response = await fetch(url);
return response;
} catch (error) {
throw error;
}
}
}
async function getRemoteURL(ports, path) {
const remoteURLInstance = new urlBuilder(ports, path);
const result = await remoteURLInstance.findFirstSuccessfulHost();
if (result) {
const fullUrl = `${result.host}:${result.port}${result.path}`;
console.log(`First successful host: ${fullUrl}`);
return fullUrl;
} else {
console.log('No successful host found.');
return null;
}
}
module.exports = {
getRemoteURL,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment