I have implemented a component that displays news based on a specified date range. Currently, the API I am using only provides data for the past 90 days. However, I aim to enhance this component by allowing users to select a date range of 1 year. To achieve this, I plan to divide the 1-year period into chunks of 90 days and fetch data accordingly. Additionally, I need the request to halt after retrieving the first set of data within the 90-day interval.
For instance:
startDate = 2021-12-27
endDate = 2022-12-27
Identify the date that is 90 days before the chosen endDate (startDate = 2022-10-27). If there is data available, the loop should break. Otherwise, the system should send a request for the previous 90-day period.
This is my code:
function requestToDataNews(startDate, endDate) {
return new Promise((resolve, reject) => {
http.get(`/test=&start_date=${startDate}&end_date=${endDate}`, { timeout: 40000 }
)
.then((response) => {
if(response.data.response_code === 200){
resolve(response.data);
} else {
reject(response.data);
}
})
.catch((error) => {
reject(error);
}).finally(() => {
commit('loadingBar', false);
});
});
}
commit('loadingBar', true);
let startDate = '2022-12-27';
let endDate = '2021-12-27';
const differentDays = tools.getDifferentDaysRange(endDate, startDate, 'days');
const currentNewsData = [];
if (differentDays > 90 && differentDays <= 365) {
for (let i = 0; i < Math.ceil(differentDays / 90); i += 1){
startDate = moment(endDate).subtract('months', 2).format('YYYY-MM-DD');
const newsData = requestToDataNews(startDate, endDate);
if (newsData.is_success) {
currentNewsData.push(...newsData.data);
}
}
}
}
PLEASE NOTE: There seems to be an issue with my code's functionality.