Skip to content

Instantly share code, notes, and snippets.

@hanicker
Created November 11, 2025 22:59
Show Gist options
  • Select an option

  • Save hanicker/867520720cfef58bb8bc304ab2594578 to your computer and use it in GitHub Desktop.

Select an option

Save hanicker/867520720cfef58bb8bc304ab2594578 to your computer and use it in GitHub Desktop.
Info RCA Targa via Javascript
/**
* Recupera le informazioni RCA di una o più targhe italiane tramite API RapidAPI
* @param {string|string[]} targa - La targa o array di targhe da cercare (es. "AB123CD" o ["AB123CD", "XY456ZW"])
* @param {string} operazione - Tipo di operazione (default: "rca")
* @returns {Promise<Object>} - Promessa che si risolve con i dati delle targhe
*/
async function getInfoTarga(targa, operazione = 'rca') {
const API_KEY = 'CODICE API';
const API_HOST = 'informazioni-targhe.p.rapidapi.com';
const SUBMIT_URL = 'https://informazioni-targhe.p.rapidapi.com/job/submit';
const POLLING_INTERVAL = 2000; // Intervallo di polling in millisecondi
const MAX_ATTEMPTS = 300; // Numero massimo di tentativi
/**
* Effettua una richiesta XHR e restituisce una Promise
* @param {string} method - Metodo HTTP (GET o POST)
* @param {string} url - URL della richiesta
* @param {Object|null} data - Dati da inviare (per POST)
* @returns {Promise<Object>} - Risposta della richiesta
*/
function makeRequest(method, url, data = null) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
// Imposta gli header richiesti da RapidAPI
xhr.setRequestHeader('x-rapidapi-key', API_KEY);
xhr.setRequestHeader('x-rapidapi-host', API_HOST);
if (method === 'POST' && data) {
xhr.setRequestHeader('Content-Type', 'application/json');
}
// Gestisce la risposta
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const response = JSON.parse(xhr.responseText);
resolve(response);
} catch (e) {
reject(new Error('Errore nel parsing della risposta JSON: ' + xhr.responseText));
}
} else {
reject(new Error(`Errore HTTP: ${xhr.status} - ${xhr.statusText} - ${xhr.responseText}`));
}
};
// Gestisce gli errori di rete
xhr.onerror = function() {
reject(new Error('Errore di rete durante la richiesta'));
};
// Gestisce il timeout
xhr.ontimeout = function() {
reject(new Error('Timeout della richiesta'));
};
xhr.timeout = 15000; // Timeout di 15 secondi
// Invia la richiesta
if (data) {
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
});
}
/**
* Funzione helper per attendere un certo periodo
* @param {number} ms - Millisecondi da attendere
* @returns {Promise<void>}
*/
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
try {
// Converte la targa in array se è una stringa singola
const targhe = Array.isArray(targa) ? targa : [targa];
console.log(`Richiesta informazioni per ${targhe.length} targa/e:`, targhe);
// STEP 1: Effettua la richiesta POST per sottomettere il job
const requestBody = {
targhe: targhe,
op: operazione
};
const submitResponse = await makeRequest('POST', SUBMIT_URL, requestBody);
console.log('Job sottomesso:', submitResponse);
// Verifica se la risposta contiene un job_id
if (!submitResponse.job_id) {
throw new Error('La risposta non contiene un job_id');
}
const jobId = submitResponse.job_id;
const statusUrl = `https://informazioni-targhe.p.rapidapi.com/job/status?job=${jobId}`;
const retrieveUrl = `https://informazioni-targhe.p.rapidapi.com/job/retrieve?job=${jobId}`;
console.log('Job ID:', jobId);
// STEP 2: Polling per verificare lo stato del job
let attempts = 0;
let isCompleted = false;
while (attempts < MAX_ATTEMPTS && !isCompleted) {
attempts++;
console.log(`Controllo stato job - tentativo ${attempts}/${MAX_ATTEMPTS}...`);
// Attende prima di fare il polling
await sleep(POLLING_INTERVAL);
// Effettua la richiesta GET per verificare lo stato del job
const statusResponse = await makeRequest('GET', statusUrl);
console.log('Stato job:', statusResponse);
// Verifica se il job è completato controllando completed === true
if (statusResponse.completed === true) {
isCompleted = true;
console.log('Job completato! Recupero i dati...');
} else if (statusResponse.error || statusResponse.failed === true) {
throw new Error(`Job fallito: ${statusResponse.error || statusResponse.message || 'Errore sconosciuto'}`);
} else {
// Job ancora in elaborazione
console.log(`Job in elaborazione... (completed: ${statusResponse.completed})`);
}
}
// Verifica se il job è stato completato o se abbiamo raggiunto il timeout
if (!isCompleted) {
throw new Error('Timeout: il job non è stato completato entro il tempo massimo');
}
// STEP 3: Recupera i risultati del job
console.log('Recupero i risultati del job...');
const result = await makeRequest('GET', retrieveUrl);
console.log('Risultati ricevuti con successo!');
// Se abbiamo cercato una sola targa, restituiamo solo quel risultato
// altrimenti restituiamo l'intero oggetto
if (targhe.length === 1 && result.data && Array.isArray(result.data)) {
return result.data[0] || result;
}
return result;
} catch (error) {
console.error('Errore durante la richiesta:', error);
throw error;
}
}
getInfoTarga('CN160TB')
.then(data => {
console.log('Informazioni targa:', data[0].data);
})
.catch(error => {
console.error('Errore:', error.message);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment