-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
72 lines (65 loc) · 2.63 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const axios = require("axios");
// Define your API key and base URL
const apiKey = "c6bea919-62f7-48ba-bf16-c8da52476c77";
const baseURL = "http://api.airvisual.com/v2";
async function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function getAirQualityData(cityName, stateName, countryName) {
const airQualityURL = `${baseURL}/city?city=${cityName}&state=${stateName}&country=${countryName}&key=${apiKey}`;
try {
const response = await axios.get(airQualityURL);
if (response.data.status === "success") {
const aqi = response.data.data.current.pollution.aqius;
console.log(`AQI for ${cityName}, ${stateName}, ${countryName}: ${aqi}`);
} else {
console.log(`API call failed for ${cityName}, ${stateName}, ${countryName}`);
}
} catch (error) {
console.error(`Error fetching air quality data for ${cityName}, ${stateName}, ${countryName}: ${error}`);
}
}
async function getCitiesForStateAndCountry(stateName, countryName) {
const cityListURL = `${baseURL}/cities?state=${stateName}&country=${countryName}&key=${apiKey}`;
try {
const response = await axios.get(cityListURL);
const cities = response.data.data;
console.log(`Cities for ${stateName}, ${countryName}:`, cities);
for (const city of cities) {
await getAirQualityData(city.city, stateName, countryName);
await sleep(10000); // Sleep for 10 seconds between city API calls
}
} catch (error) {
console.error(`Error fetching cities for ${stateName}, ${countryName}: ${error}`);
}
}
async function getStatesForCountry(countryName) {
const stateListURL = `${baseURL}/states?country=${countryName}&key=${apiKey}`;
try {
const response = await axios.get(stateListURL);
const states = response.data.data;
console.log(`States for ${countryName}:`, states);
for (const state of states) {
await getCitiesForStateAndCountry(state.state, countryName);
await sleep(10000); // Sleep for 10 seconds between state API calls
}
} catch (error) {
console.error(`Error fetching states for ${countryName}: ${error}`);
}
}
async function getAllCountries() {
const countryListURL = `${baseURL}/countries?key=${apiKey}`;
try {
const response = await axios.get(countryListURL);
const countries = response.data.data;
console.log("All countries:", countries);
for (const country of countries) {
await getStatesForCountry(country.country);
await sleep(10000); // Sleep for 10 seconds between country API calls
}
} catch (error) {
console.error("Error fetching countries:", error);
}
}
// Call the function to start the process
getAllCountries();