Convertido código para classe

This commit is contained in:
Luiz F Picolo 2023-06-13 15:17:12 -04:00
parent eead1cca3d
commit 0c55cc3a27

View File

@ -1,49 +1,56 @@
const axios = require('axios'); const axios = require('axios');
function checkSiteStatus(site) { class InstanceChecker {
return Promise.race([ constructor() {
axios.get(`https://${site}/api/v1/instance`), this.axiosInstance = axios.create();
new Promise((resolve, reject) => { }
setTimeout(() => reject(new Error('Tempo de espera excedido')), 30000);
})
])
.then(response => {
return { site, status: 'online' };
})
.catch(error => {
return { site, status: 'offline' };
});
}
async function fetchSitesFromAPI() { async checkInstanceStatus(instance) {
try { try {
const response = await axios.get('https://mastodon.social/api/v1/instance/peers'); const response = await Promise.race([
this.axiosInstance.get(`https://${instance}/api/v1/instance`),
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Tempo de espera excedido')), 6000);
})
]);
return { instance, status: true };
} catch (error) {
return { instance, status: false };
}
}
async fetchPeersFromAPI() {
try {
const response = await this.axiosInstance.get('https://mastodon.social/api/v1/instance/peers');
return response.data; return response.data;
} catch (error) { } catch (error) {
console.error('Erro ao buscar sites da API:', error.message); console.error('Erro ao buscar peers da API:', error.message);
return []; return [];
} }
} }
async function checkAllSitesStatus() { async checkPeersStatus() {
const sites = await fetchSitesFromAPI(); const peers = await this.fetchPeersFromAPI();
if (sites.length === 0) { if (peers.length === 0) {
console.log('Nenhum site encontrado na API.'); console.log('Nenhum peer encontrado na API.');
return; return;
} }
const results = []; const results = [];
for (const site of sites) { for (const peer of peers) {
try { try {
const result = await checkSiteStatus(site); const result = await this.checkInstanceStatus(peer);
console.log(`${result.site} está ${result.status}.`); console.log(`${result.instance} está ${result.status}.`);
results.push(result); results.push(result);
} catch (error) { } catch (error) {
console.error(`Erro ao verificar o status de ${site}:`, error.message); console.error(`Erro ao verificar o status de ${peer}:`, error.message);
}
} }
} }
} }
checkAllSitesStatus(); const instanceChecker = new InstanceChecker();
instanceChecker.checkPeersStatus();