/
app.js
76 lines (66 loc) · 1.6 KB
/
app.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
73
74
75
const https = require('https');
getBordersInfo("ESP", showErrorOrCountries)
console.log("Peticion realizada");
console.log("---");
function getBordersInfo(code, callback) {
getCountryInfo(code, function (err, country) {
if (err) {
callback(err);
} else {
let globalErr = false;
let borders = [];
for (let code of country.borders) {
getCountryInfo(code, function (err2, countryBorder) {
if (err2) {
callback(err2);
globalErr = true;
} else {
if (!globalErr) {
borders.push(countryBorder);
if (borders.length === country.borders.length) {
callback(undefined, borders);
}
}
}
});
}
}
});
}
function getCountryInfo(code, callback) {
const url = `https://restcountries.com/v3.1/alpha/${code}`;
console.log(url);
https
.get(url, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
let country = JSON.parse(data)[0];
callback(undefined, country);
});
})
.on("error", (err) => {
callback(err);
});
}
function showErrorOrCountries(err, countries) {
if (err) {
console.log(err);
} else {
for (let country of countries) {
showErrorOrCountry(null, country);
}
}
}
function showErrorOrCountry(err, country) {
if (err) {
console.log("Error: " + err.message);
} else {
for (let key in country) {
console.log(`${key}: ${country[key]}`);
}
console.log(`\n`);
}
}