geoshell
Version:
A CLI to fetch real-time geo-data from your terminal
59 lines (52 loc) • 1.83 kB
JavaScript
/**
* Country command implementation
*/
const api = require('../utils/api');
const { CountryNotFound } = require('../utils/errors');
/**
* Get country information
*
* @param {string} name - Country name or ISO code
* @param {Object} options - Options
* @param {string[]} options.fields - Specific fields to return
* @returns {Promise<Object>} Country information
*/
async function country(name, options = {}) {
try {
const url = `${api.BASE_URLS.countries}/name/${encodeURIComponent(name)}`;
const data = await api.makeRequest(url);
if (!data || data.length === 0) {
throw new CountryNotFound(`Country '${name}' not found`);
}
const countryData = data[0];
const countryInfo = {
name: countryData.name?.common || name,
capital: countryData.capital?.[0] || 'Unknown',
population: countryData.population || 0,
area: countryData.area || 0,
currency: Object.keys(countryData.currencies || {})[0] || 'Unknown',
languages: Object.values(countryData.languages || {}).join(', ') || 'Unknown',
region: countryData.region || 'Unknown',
subregion: countryData.subregion || 'Unknown',
borders: countryData.borders?.join(', ') || 'None',
flag: countryData.flags?.png || '',
};
// Filter fields if specified
if (options.fields) {
const filteredInfo = {};
options.fields.forEach(field => {
if (countryInfo[field] !== undefined) {
filteredInfo[field] = countryInfo[field];
}
});
return filteredInfo;
}
return countryInfo;
} catch (error) {
if (error instanceof CountryNotFound) {
throw error;
}
throw new Error(`Failed to fetch country data: ${error.message}`);
}
}
module.exports = country;