async function fetchNews(type, symbol, months, finnhub_apiKey) {
const today = new Date();
const monthsAgo = new Date();
monthsAgo.setMonth(today.getMonth() - months);
const newsData = [];
let currentStartDate = new Date(monthsAgo);
if (type === 'generalxx') {
const response = await fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=${newsapi_apiKey}`);
const data = await response.json();
newsData.push(...data);
} else {
while (currentStartDate <= today) {
const currentEndDate = new Date(currentStartDate);
currentEndDate.setDate(currentEndDate.getDate() + 14);
if (currentEndDate > today) {
currentEndDate.setDate(today.getDate());
}
const from = dateFormatter(currentStartDate);
const to = dateFormatter(currentEndDate);
try {
let response = null;
if (type === 'stock') {
response = await fetch(`https://finnhub.io/api/v1/company-news?symbol=${symbol}&from=${from}&to=${to}&token=${finnhub_apiKey}`);
} else {
response = await fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=${newsapi_apiKey}`);
}
const data = await response.json();
newsData.push(...data);
} catch (error) {
console.error(`Error fetching news from ${from} to ${to}:`, error);
}
currentStartDate.setDate(currentStartDate.getDate() + 15);
}
}
return newsData;
}