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 15:09:24 -06:00
|
|
|
// Extract league ID from the URL
|
|
|
|
|
const leagueID = req.params.leagueID;
|
2024-04-11 08:49:19 -06:00
|
|
|
|
2024-04-13 15:09:24 -06:00
|
|
|
// Make GET request to the API endpoint using the league ID
|
|
|
|
|
const response = await axios.get(`http://api.football-data.org/v4/competitions/${leagueID}/standings?season`, {
|
|
|
|
|
headers: {
|
|
|
|
|
'X-Auth-Token': '0aa1ed31245d4a36b1ef5a79150324b3', // Add your API key here
|
|
|
|
|
},
|
|
|
|
|
});
|
2024-04-11 08:49:19 -06:00
|
|
|
|
2024-04-13 15:09:24 -06:00
|
|
|
// Extract relevant data from the API response
|
|
|
|
|
const leagueData = response.data;
|
2024-04-11 08:49:19 -06:00
|
|
|
|
2024-04-13 15:09:24 -06:00
|
|
|
// Attach the data to res.locals
|
2024-04-17 21:45:27 -06:00
|
|
|
//res.locals.username = req.session.user.username;
|
2024-04-17 18:06:45 -06:00
|
|
|
console.log(req.session.user)
|
2024-04-13 15:58:02 -06:00
|
|
|
res.locals.league = {
|
2024-04-13 18:45:55 -06:00
|
|
|
area: {
|
|
|
|
|
league_flag: leagueData.area.flag,
|
|
|
|
|
},
|
2024-04-13 15:09:24 -06:00
|
|
|
competition: {
|
|
|
|
|
league_id: leagueData.competition.id,
|
|
|
|
|
league_name: leagueData.competition.name,
|
|
|
|
|
league_emblem: leagueData.competition.emblem
|
|
|
|
|
},
|
|
|
|
|
standings: leagueData.standings[0].table.map(team => ({
|
|
|
|
|
table: {
|
|
|
|
|
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 18:40:46 -06:00
|
|
|
games_played: team.playedGames,
|
|
|
|
|
wins: team.won,
|
|
|
|
|
losses: team.lost,
|
|
|
|
|
draws: team.draw,
|
|
|
|
|
goal_difference: team.goalDifference,
|
|
|
|
|
points: team.points
|
2024-04-17 18:06:45 -06:00
|
|
|
})),
|
2024-04-13 15:58:02 -06:00
|
|
|
};
|
2024-04-11 08:49:19 -06:00
|
|
|
next();
|
2024-04-13 15:09:24 -06:00
|
|
|
} catch (error) {
|
2024-04-13 14:25:34 -06:00
|
|
|
console.error('Error fetching leagues data:', error);
|
2024-04-13 15:58:02 -06:00
|
|
|
res.locals.league = null; // Set to null if there's an error
|
2024-04-11 08:49:19 -06:00
|
|
|
next(); // Call next middleware or route handler
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2024-04-13 14:25:34 -06:00
|
|
|
module.exports = fetchLeaguesData;
|