2024-04-11 08:49:19 -06:00
|
|
|
const axios = require('axios');
|
|
|
|
|
|
2024-04-13 14:25:34 -06:00
|
|
|
// Middleware function to fetch leagues data
|
|
|
|
|
const fetchLeaguesData = async (req, res, next) => {
|
2024-04-11 08:49:19 -06:00
|
|
|
try {
|
2024-04-13 14:25:34 -06:00
|
|
|
// Array of years to fetch leagues data
|
|
|
|
|
const league_ids = [2021]; /* Add more league IDs if needed */
|
2024-04-11 08:49:19 -06:00
|
|
|
|
2024-04-13 14:25:34 -06:00
|
|
|
// Array to store all leagues data
|
2024-04-11 08:49:19 -06:00
|
|
|
let allLeagues = [];
|
|
|
|
|
|
2024-04-13 14:25:34 -06:00
|
|
|
// Loop through each year and fetch leagues data
|
2024-04-11 08:49:19 -06:00
|
|
|
for (const league_id of league_ids) {
|
|
|
|
|
const response = await axios({
|
2024-04-13 14:25:34 -06:00
|
|
|
url: `http://api.football-data.org/v4/competitions/${league_id}/standings?season`,
|
2024-04-11 08:49:19 -06:00
|
|
|
method: 'GET',
|
|
|
|
|
headers: {
|
|
|
|
|
'X-Auth-Token': '0aa1ed31245d4a36b1ef5a79150324b3', // Add your API key here
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Extract relevant data from the API response
|
2024-04-13 14:25:34 -06:00
|
|
|
const league_data = response.data.standings[0].table.map(team => ({
|
2024-04-11 08:49:19 -06:00
|
|
|
competition: {
|
2024-04-13 14:25:34 -06:00
|
|
|
league_id: response.data.competition.id,
|
|
|
|
|
league_name: response.data.competition.name,
|
|
|
|
|
league_emblem: response.data.competition.emblem
|
2024-04-11 08:49:19 -06:00
|
|
|
},
|
|
|
|
|
standings: {
|
|
|
|
|
table: {
|
2024-04-13 14:25:34 -06:00
|
|
|
league_position: team.position,
|
|
|
|
|
team_id: team.team.id,
|
|
|
|
|
team_name: team.team.name,
|
|
|
|
|
team_crest: team.team.crest
|
2024-04-11 08:49:19 -06:00
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
}));
|
|
|
|
|
|
2024-04-13 14:25:34 -06:00
|
|
|
// Concatenate leagues data to allLeagues array
|
|
|
|
|
allLeagues = allLeagues.concat(league_data);
|
2024-04-11 08:49:19 -06:00
|
|
|
}
|
|
|
|
|
|
2024-04-13 14:25:34 -06:00
|
|
|
// Attach all leagues data to res.locals
|
2024-04-11 08:49:19 -06:00
|
|
|
res.locals.leagues = allLeagues;
|
|
|
|
|
next();
|
2024-04-13 14:25:34 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
catch (error)
|
|
|
|
|
{
|
|
|
|
|
console.error('Error fetching leagues data:', error);
|
2024-04-11 08:49:19 -06:00
|
|
|
res.locals.leagues = []; // Set an empty array if there's an error
|
|
|
|
|
next(); // Call next middleware or route handler
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2024-04-13 14:25:34 -06:00
|
|
|
module.exports = fetchLeaguesData;
|