Created
November 11, 2025 23:01
-
-
Save hanicker/2848a8903de7eb07ac134d5df1b60f1a to your computer and use it in GitHub Desktop.
rca targa italiana nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const https = require('https'); | |
| /** | |
| * 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 = 'RAPID API KEY'; | |
| const API_HOST = 'informazioni-targhe.p.rapidapi.com'; | |
| const POLLING_INTERVAL = 2000; // Intervallo di polling in millisecondi | |
| const MAX_ATTEMPTS = 300; // Numero massimo di tentativi | |
| /** | |
| * Effettua una richiesta HTTPS e restituisce una Promise | |
| * @param {string} method - Metodo HTTP (GET o POST) | |
| * @param {string} path - Path della richiesta | |
| * @param {Object|null} data - Dati da inviare (per POST) | |
| * @returns {Promise<Object>} - Risposta della richiesta | |
| */ | |
| function makeRequest(method, path, data = null) { | |
| return new Promise((resolve, reject) => { | |
| const options = { | |
| hostname: API_HOST, | |
| port: 443, | |
| path: path, | |
| method: method, | |
| headers: { | |
| 'x-rapidapi-key': API_KEY, | |
| 'x-rapidapi-host': API_HOST | |
| }, | |
| timeout: 15000 // Timeout di 15 secondi | |
| }; | |
| // Aggiungi Content-Type per le richieste POST | |
| if (method === 'POST' && data) { | |
| const postData = JSON.stringify(data); | |
| options.headers['Content-Type'] = 'application/json'; | |
| options.headers['Content-Length'] = Buffer.byteLength(postData); | |
| } | |
| const req = https.request(options, (res) => { | |
| let responseData = ''; | |
| // Accumula i dati della risposta | |
| res.on('data', (chunk) => { | |
| responseData += chunk; | |
| }); | |
| // Gestisce la fine della risposta | |
| res.on('end', () => { | |
| if (res.statusCode >= 200 && res.statusCode < 300) { | |
| try { | |
| const response = JSON.parse(responseData); | |
| resolve(response); | |
| } catch (e) { | |
| reject(new Error('Errore nel parsing della risposta JSON: ' + responseData)); | |
| } | |
| } else { | |
| reject(new Error(`Errore HTTP: ${res.statusCode} - ${res.statusMessage} - ${responseData}`)); | |
| } | |
| }); | |
| }); | |
| // Gestisce gli errori della richiesta | |
| req.on('error', (error) => { | |
| reject(new Error('Errore di rete durante la richiesta: ' + error.message)); | |
| }); | |
| // Gestisce il timeout | |
| req.on('timeout', () => { | |
| req.destroy(); | |
| reject(new Error('Timeout della richiesta')); | |
| }); | |
| // Invia i dati se è una richiesta POST | |
| if (method === 'POST' && data) { | |
| req.write(JSON.stringify(data)); | |
| } | |
| req.end(); | |
| }); | |
| } | |
| /** | |
| * 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', '/job/submit', 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; | |
| 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', `/job/status?job=${jobId}`); | |
| 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', `/job/retrieve?job=${jobId}`); | |
| 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; | |
| } | |
| } | |
| // ESEMPIO DI UTILIZZO | |
| getInfoTarga('CN161TB') | |
| .then(data => { | |
| console.log('Informazioni targa:', data); | |
| }) | |
| .catch(error => { | |
| console.error('Errore:', error.message); | |
| }); | |
| // Esporta la funzione per essere utilizzata in altri moduli | |
| module.exports = { getInfoTarga }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment