UNPKG

geoshell

Version:

A CLI to fetch real-time geo-data from your terminal

83 lines (75 loc) 2.02 kB
/** * API utilities */ const axios = require('axios'); const { APIError } = require('./errors'); // Configuration const BASE_URLS = { countries: 'https://restcountries.com/v3.1', weather: 'https://api.openweathermap.org/data/2.5', holidays: 'https://date.nager.at/api/v3', news: 'https://newsapi.org/v2' }; /** * Make HTTP request * * @param {string} url - URL to request * @param {Object} options - Request options * @returns {Promise<Object>} Response data */ async function makeRequest(url, options = {}) { try { const response = await axios({ method: options.method || 'get', url, params: options.params, headers: options.headers, timeout: options.timeout || 10000 }); return response.data; } catch (error) { if (error.response) { // Server responded with non-2xx status if (error.response.status === 404) { return null; // Let the caller handle 404 } throw new APIError(`API Error: ${error.response.status} - ${error.response.statusText}`); } else if (error.request) { // Request made but no response received throw new APIError('No response from server'); } else { // Error setting up request throw new APIError(`Request error: ${error.message}`); } } } /** * Get country code from name * * @param {string} country - Country name * @returns {string} Country code */ function getCountryCode(country) { const countryCodes = { 'usa': 'us', 'united states': 'us', 'canada': 'ca', 'germany': 'de', 'france': 'fr', 'japan': 'jp', 'brazil': 'br', 'uk': 'gb', 'united kingdom': 'gb', 'italy': 'it', 'spain': 'es', 'australia': 'au', 'india': 'in', 'china': 'cn' }; return countryCodes[country.toLowerCase()] || country.toLowerCase().substring(0, 2); } module.exports = { BASE_URLS, makeRequest, getCountryCode };