UNPKG

geoshell

Version:

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

82 lines (70 loc) 2.21 kB
/** * News command implementation */ const api = require('../utils/api'); /** * Get latest news for a country * * @param {string} country - Country name * @param {Object} options - Options * @param {number} options.limit - Number of articles to return * @returns {Promise<Array>} List of news articles */ async function news(country, options = {}) { const limit = options.limit || 10; const apiKey = process.env.NEWS_API_KEY; if (!apiKey) { // Return mock data if no API key return getMockNews(country, limit); } try { const url = `${api.BASE_URLS.news}/top-headlines`; const params = { country: api.getCountryCode(country), apiKey: apiKey, pageSize: limit }; const data = await api.makeRequest(url, { params }); if (!data || !data.articles) { return getMockNews(country, limit); } return data.articles.map(article => ({ title: article.title, description: article.description, url: article.url, published_at: article.publishedAt, source: article.source.name })); } catch (error) { // Return mock data if API fails return getMockNews(country, limit); } } /** * Get mock news data * * @param {string} country - Country name * @param {number} limit - Number of articles to return * @returns {Array} Mock news data */ function getMockNews(country, limit = 10) { const articles = []; const topics = [ 'Politics', 'Economy', 'Technology', 'Sports', 'Entertainment', 'Health', 'Science', 'Environment' ]; for (let i = 0; i < limit; i++) { const topic = topics[Math.floor(Math.random() * topics.length)]; const date = new Date(); date.setHours(date.getHours() - Math.floor(Math.random() * 24)); articles.push({ title: `${topic} news from ${country}: Article ${i + 1}`, description: `This is a mock news article about ${topic.toLowerCase()} in ${country}.`, url: 'https://example.com/news', published_at: date.toISOString(), source: 'GeoShell News' }); } return articles; } module.exports = news;