Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const router = express.Router();
- const axios = require('axios');
- const app = express();
- // Starting the Express server
- const PORT = 3030;
- app.listen(PORT, () => {
- console.log(`Express server listening on port ${PORT}`);
- });
- /**
- * Handles POST request for player search.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.body - The request body.
- * @param {string} req.body.barName - The player's name.
- * @param {Object} res - The response object.
- * @returns {Object} - JSON response with the players data.
- */
- router.post('/playerbar', async (req, res) => {
- try {
- const playerName = req.body.barName; // Extract the player's name from the request
- // Forward the request to the Spring server using axios
- const response = await axios.post('http://localhost:8080/player', playerName);
- const players = response.data;
- // Forward the response from the Spring server to the client
- res.json(players);
- } catch (error) {
- res.status(500).send('Error during player search');
- }
- });
- /**
- * Handles POST request for club search.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.body - The request body.
- * @param {string} req.body.barName - The club's name.
- * @param {Object} res - The response object.
- * @returns {Object} - JSON response with the clubs data.
- */
- router.post('/clubbar', async (req, res) => {
- try {
- const clubName = req.body.barName; // Extract the club's name from the request
- // Forward the request to the Spring server using axios
- const response = await axios.post('http://localhost:8080/club', clubName);
- const clubs = response.data;
- // Forward the response from the Spring server to the client
- res.json(clubs);
- } catch (error) {
- res.status(500).send('Error during club search');
- }
- });
- /**
- * Handles POST request for player details.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.body - The request body.
- * @param {string} req.body.barName - The player's name.
- * @param {Object} res - The response object.
- */
- router.post('/player', async (req, res) => {
- try {
- const playerName = req.body.barName.toLowerCase(); // Extract the player's name from the request
- // Forward the request to the Spring server using axios
- const response = await axios.post('http://localhost:8080/player', playerName);
- const players = response.data;
- // Extract data from the first player in the list (presumably there is only one)
- const playerData = players[0];
- // Pass the player's name as the page title
- res.render('player', {
- title: playerData.name,
- playerId: playerData.playerId,
- firstName: playerData.firstName,
- lastName: playerData.lastName,
- name: playerData.name,
- lastSeason: playerData.lastSeason,
- currentClubId: playerData.currentClubId,
- playerCode: playerData.playerCode,
- countryOfBirth: playerData.countryOfBirth,
- cityOfBirth: playerData.cityOfBirth,
- countryOfCitizenship: playerData.countryOfCitizenship,
- dateOfBirth: playerData.dateOfBirth,
- subPosition: playerData.subPosition,
- position: playerData.position,
- foot: playerData.foot,
- heightInCm: playerData.heightInCm,
- marketValueInEur: playerData.marketValueInEur,
- highestMarketValueInEur: playerData.highestMarketValueInEur,
- contractExpirationDate: playerData.contractExpirationDate,
- agentName: playerData.agentName,
- imageUrl: playerData.imageUrl,
- url: playerData.url,
- currentClubDomesticCompetitionId: playerData.currentClubDomesticCompetitionId,
- currentClubName: playerData.currentClubName
- });
- } catch (error) {
- console.error('Error during player search:', error);
- res.status(500).send('Error during player search');
- }
- });
- /**
- * Handles POST request for club details.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.body - The request body.
- * @param {string} req.body.barName - The club's name.
- * @param {Object} res - The response object.
- */
- router.post('/club', async (req, res) => {
- try {
- const clubName = req.body.barName.toLowerCase(); // Extract the club's name from the request
- // Forward the request to the Spring server using axios
- const response = await axios.post('http://localhost:8080/club', clubName);
- const clubs = response.data;
- // Extract data from the first club in the list (presumably there is only one)
- const clubData = clubs[0];
- // Pass the club's name as the page title
- res.render('club', {
- title: clubData.name,
- clubId: clubData.clubId,
- clubCode: clubData.clubCode,
- name: clubData.name,
- domesticCompetitionId: clubData.domesticCompetitionId,
- totalMarketValue: clubData.totalMarketValue,
- squadSize: clubData.squadSize,
- averageAge: clubData.averageAge,
- foreignersNumber: clubData.foreignersNumber,
- foreignersPercentage: clubData.foreignersPercentage,
- nationalTeamPlayers: clubData.nationalTeamPlayers,
- stadiumName: clubData.stadiumName,
- stadiumSeats: clubData.stadiumSeats,
- netTransferRecord: clubData.netTransferRecord,
- coachName: clubData.coachName,
- lastSeason: clubData.lastSeason,
- url: clubData.url
- });
- } catch (error) {
- console.error('Error during club search:', error);
- res.status(500).send('Error during club search');
- }
- });
- /**
- * Handles GET request for player information by player ID.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.params - The request parameters.
- * @param {string} req.params.playerId - The player's ID.
- * @param {Object} res - The response object.
- */
- router.get('/player/:playerId', async (req, res) => {
- try {
- const playerId = req.params.playerId; // Extract the player's ID from the request
- // Forward the request to the Spring server using axios
- const response = await axios.get(`http://localhost:8080/player/${playerId}`);
- const players = response.data;
- const playerData = players[0];
- // Retrieve the player's team standings
- const responseClub = await axios.get(`http://localhost:8080/club/${playerData.currentClubId}`);
- const club = responseClub.data;
- const response3 = await axios.get(`http://localhost:3001/game/${club[0].domesticCompetitionId}/2023`);
- const gameMongo = response3.data; // gameMongo is for games informations coming from Mongodb, like standings, goals, subs, cards etc
- // Fetch player's appearance stats for the specified year
- const totalCountStats = await axios.get(`http://localhost:3001/appearancesCount/${playerId}`);
- const app = totalCountStats.data; // App is for appearances stats (adding goal assist and cards)
- const lastYear = await axios.get(`http://localhost:3001/appearancesCount/${playerId}/2023`);
- const lastYearData = lastYear.data;
- const ris4 = await axios.get(`http://localhost:3001/clubPlayed/${playerId}`);
- const clubPlayed = ris4.data;
- const clubDetails = [];
- for (let i = 0; i < clubPlayed.length; i++) {
- const club_id = clubPlayed[i].player_club_id;
- if (isNaN(club_id) || club_id === '\\N') {
- clubDetails.push({
- date: clubPlayed[i].date,
- id: club_id,
- club_name: "Unknown"
- });
- } else {
- try {
- const springResponse = await axios.get(`http://localhost:8080/club/${club_id}`);
- const club = springResponse.data;
- const name = club[0].name;
- clubDetails.push({
- date: clubPlayed[i].date,
- id: club_id,
- club_name: name
- });
- } catch (error) {
- console.error("Error fetching club details:", error);
- clubDetails.push({
- date: clubPlayed[i].date,
- id: club_id,
- club_name: "Unknown"
- });
- }
- }
- }
- const market = await axios.get(`http://localhost:3001/playerValue/${playerId}`);
- const marketValue = market.data;
- // Pass the player's name as the page title
- res.render('player', {
- title: playerData.name,
- playerId: playerData.playerId,
- firstName: playerData.firstName,
- lastName: playerData.lastName,
- name: playerData.name,
- lastSeason: playerData.lastSeason,
- currentClubId: playerData.currentClubId,
- playerCode: playerData.playerCode,
- countryOfBirth: playerData.countryOfBirth,
- cityOfBirth: playerData.cityOfBirth,
- countryOfCitizenship: playerData.countryOfCitizenship,
- dateOfBirth: playerData.dateOfBirth,
- subPosition: playerData.subPosition,
- position: playerData.position,
- foot: playerData.foot,
- heightInCm: playerData.heightInCm,
- marketValueInEur: playerData.marketValueInEur,
- highestMarketValueInEur: playerData.highestMarketValueInEur,
- contractExpirationDate: playerData.contractExpirationDate,
- agentName: playerData.agentName,
- imageUrl: playerData.imageUrl,
- url: playerData.url,
- currentClubDomesticCompetitionId: playerData.currentClubDomesticCompetitionId,
- currentClubName: playerData.currentClubName,
- gameMongo,
- app,
- clubDetails,
- marketValue,
- lastYearData
- });
- } catch (error) {
- res.render('error');
- }
- });
- /**
- * Handles GET request for club information by club ID.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.params - The request parameters.
- * @param {string} req.params.clubId - The club's ID.
- * @param {Object} res - The response object.
- */
- router.get('/club/:clubId', async (req, res) => {
- try {
- const clubId = req.params.clubId; // Extract the club's ID from the request
- // Forward the request to the Spring server using axios
- const response = await axios.get(`http://localhost:8080/club/${clubId}`);
- const clubs = response.data;
- const response2 = await axios.post(`http://localhost:8080/club/${clubId}/player`);
- const players = response2.data;
- const response3 = await axios.get(`http://localhost:3001/game/${clubs[0].domesticCompetitionId}/2023`);
- const gameMongo = response3.data; // gameMongo is for games informations coming from Mongodb, like standings, goals, subs, cards etc
- console.log("aaaaa ");
- const response4 = await axios.get(`http://localhost:3001/coach/${clubId}`);
- const coach = response4.data; //get the coach of the club, according to the last game
- console.log(response4.data);
- // Organize players by position
- const goalkeepers = players.filter(player => player.position === 'Goalkeeper');
- const defenders = players.filter(player => player.position === 'Defender');
- const midfielders = players.filter(player => player.position === 'Midfield');
- const forwards = players.filter(player => player.position === 'Attack');
- // Extract data from the first club in the list (presumably there is only one)
- const clubData = clubs[0];
- // Pass the club's name as the page title
- res.render('club', {
- title: clubData.name,
- clubId: clubData.clubId,
- clubCode: clubData.clubCode,
- name: clubData.name,
- domesticCompetitionId: clubData.domesticCompetitionId,
- totalMarketValue: clubData.totalMarketValue,
- squadSize: clubData.squadSize,
- averageAge: clubData.averageAge,
- foreignersNumber: clubData.foreignersNumber,
- foreignersPercentage: clubData.foreignersPercentage,
- nationalTeamPlayers: clubData.nationalTeamPlayers,
- stadiumName: clubData.stadiumName,
- stadiumSeats: clubData.stadiumSeats,
- netTransferRecord: clubData.netTransferRecord,
- coachName: coach,
- lastSeason: clubData.lastSeason,
- url: clubData.url,
- goalkeepers,
- defenders,
- midfielders,
- forwards,
- gameMongo
- });
- } catch (error) {
- res.render('error');
- }
- });
- /**
- * Handles GET request to retrieve all competitions.
- *
- * @param {Object} req - The request object.
- * @param {Object} res - The response object.
- * @returns {Object} - Renders the competition list page with competitions data.
- */
- router.get('/competitions', async (req, res) => {
- try {
- // Make a GET request to the Spring server to retrieve all competitions
- const response = await axios.get('http://localhost:8080/competitions');
- const competitions = response.data;
- // Send the competitions as a response
- res.render('competitionListPage', { competitions });
- } catch (error) {
- console.error('Error retrieving competitions:', error);
- res.status(500).send('Error retrieving competitions');
- }
- });
- /**
- * Handles GET request for competition information by competition ID.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.params - The request parameters.
- * @param {string} req.params.competitionId - The competition ID.
- * @param {Object} res - The response object.
- */
- router.get('/competitions/:competitionId', async (req, res) => {
- try {
- const competitionId = req.params.competitionId; // Extract the competition ID from the request
- // Check if the competitionId matches any of the specified values
- const specialCompetitions = ['CIT', 'NLSC', 'GRP', 'POSU', 'RUSS', 'SUC', 'USC', 'EL', 'RUP', 'BESC', 'ELQ',
- 'CGB', 'DKP', 'ECLQ', 'FAC', 'NLP', 'CDR', 'CL', 'POCP', 'KLUB', 'CLQ', 'DFL',
- 'SFA', 'UKRP', 'DFB', 'FRCH', 'SCI'];
- if (specialCompetitions.includes(competitionId)) {
- const response = await axios.get(`http://localhost:8080/competitions/${competitionId}`);
- const competitions = response.data;
- const competition = competitions[0];
- const response2 = await axios.get(`http://localhost:3001/game/${competitionId}/2023`);
- const gameMongo = response2.data; // gameMongo is for games informations coming from Mongodb, like standings, goals, subs, cards etc
- res.render('competitionCup', { competition, gameMongo }); // Pass 'competition' in singular form
- } else {
- const response = await axios.get(`http://localhost:8080/competitions/${competitionId}`);
- const competitions = response.data;
- const response2 = await axios.post(`http://localhost:8080/competitions/${competitionId}/clubs`);
- const clubs = response2.data;
- const response3 = await axios.get(`http://localhost:3001/game/${competitionId}/2023`);
- const gameMongo = response3.data;
- const competition = competitions[0];
- res.render('competition', { competition, clubs, gameMongo }); // Pass 'competition' in singular form
- }
- } catch (error) {
- res.render('error');
- }
- });
- /**
- * Handles GET request for competition information by competition ID and season.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.params - The request parameters.
- * @param {string} req.params.competitionId - The competition ID.
- * @param {string} req.params.season - The season.
- * @param {Object} res - The response object.
- */
- router.get('/competitions/:competitionId/:season', async (req, res) => {
- try {
- const competitionId = req.params.competitionId; // Extract the competition ID from the request
- const season = req.params.season;
- // Check if the competitionId matches any of the specified values
- const specialCompetitions = ['CIT', 'NLSC', 'GRP', 'POSU', 'RUSS', 'SUC', 'USC', 'EL', 'RUP', 'BESC', 'ELQ',
- 'CGB', 'DKP', 'ECLQ', 'FAC', 'NLP', 'CDR', 'CL', 'POCP', 'KLUB', 'CLQ', 'DFL',
- 'SFA', 'UKRP', 'DFB', 'FRCH', 'SCI'];
- if (specialCompetitions.includes(competitionId)) {
- const response = await axios.get(`http://localhost:8080/competitions/${competitionId}`);
- const competitions = response.data;
- const competition = competitions[0];
- const response2 = await axios.get(`http://localhost:3001/game/${competitionId}/${season}`);
- const gameMongo = response2.data; // gameMongo is for games informations coming from Mongodb, like standings, goals, subs, cards etc
- res.render('competitionCup', { competition, gameMongo }); // Pass 'competition' in singular form
- } else {
- const response = await axios.get(`http://localhost:8080/competitions/${competitionId}`);
- const competitions = response.data;
- const response2 = await axios.post(`http://localhost:8080/competitions/${competitionId}/clubs`);
- const clubs = response2.data;
- const response3 = await axios.get(`http://localhost:3001/game/${competitionId}/${season}`);
- const gameMongo = response3.data;
- const competition = competitions[0];
- res.render('competition', { competition, clubs, gameMongo }); // Pass 'competition' in singular form
- }
- } catch (error) {
- res.render('error');
- }
- });
- /**
- * Handles GET request for competition information by competition ID, season, and round.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.params - The request parameters.
- * @param {string} req.params.competitionId - The competition ID.
- * @param {string} req.params.season - The season.
- * @param {string} req.params.round - The round.
- * @param {Object} res - The response object.
- */
- router.get('/competitions/:competitionId/:season/:round', async (req, res) => {
- try {
- const competitionId = req.params.competitionId;
- const season = req.params.season;
- const round = req.params.round;
- const response = await axios.get(`http://localhost:3001/game/${competitionId}/${season}/${round}`);
- const info = response.data;
- res.render('dayMatches', { info });
- } catch (error) {
- res.render('error');
- }
- });
- /**
- * Handles GET request for competition information by competition ID and round.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.params - The request parameters.
- * @param {string} req.params.competitionId - The competition ID.
- * @param {string} req.params.round - The round.
- * @param {Object} res - The response object.
- */
- router.get('/competitions/:competitionId/:round', async (req, res) => {
- try {
- const competitionId = req.params.competitionId;
- const round = req.params.round;
- const response = await axios.get(`http://localhost:3001/game/${competitionId}/2023/${round}`);
- const info = response.data;
- res.render('dayMatches', { info });
- } catch (error) {
- res.render('error');
- res.status(500).send('Error during match search');
- }
- });
- /**
- * Handles GET request for game information by game ID.
- *
- * @param {Object} req - The request object.
- * @param {Object} req.params - The request parameters.
- * @param {string} req.params.gameId - The game ID.
- * @param {Object} res - The response object.
- */
- router.get('/gameinfo/:gameId', async (req, res) => {
- try {
- const gameId = req.params.gameId;
- const response = await axios.get(`http://localhost:3001/gameinfo/${gameId}`);
- const gameData = response.data;
- const home_id = gameData[0].home_club_id;
- const response2 = await axios.get(`http://localhost:3001/formazioni/${gameId}/${home_id}`);
- const formazioni = response2.data;
- const lunghezza = formazioni.length;
- // Check if all keys in formazioni contain empty arrays
- const isFormazioniEmpty = Object.values(formazioni).every(array => array.length === 0);
- if (isFormazioniEmpty) { // If there is no formation
- const response3 = await axios.get(`http://localhost:3001/events/${gameId}`);
- const events = response3.data;
- for (const event of events) {
- if (event.player_id) {
- event.player_name = await getPlayerName(event.player_id);
- }
- if (event.player_in_id) {
- const playerInId = event.player_in_id.split('.')[0]; // Remove the ".0" from player_in_id
- event.player_in_name = await getPlayerName(playerInId);
- }
- if (event.player_assist_id && event.player_assist_id !== '\\N') {
- event.player_assist_name = await getPlayerName(event.player_assist_id);
- }
- }
- res.render('gameNoLineup', { gameData, events });
- return;
- } else {
- const playerDetails = [];
- for (let i = 0; i < 22; i++) {
- const player_id = formazioni[i].player_id;
- if (isNaN(player_id) || player_id === '\\N') {
- playerDetails.push({
- id: player_id,
- imageUrl: "https://cdn.icon-icons.com/icons2/1729/PNG/512/footballjersey12_113031.png"
- });
- } else {
- try {
- const springResponse = await axios.get(`http://localhost:8080/player/${player_id}`);
- const player = springResponse.data;
- const url = player[0].imageUrl;
- playerDetails.push({
- id: player_id,
- imageUrl: url
- });
- } catch (error) {
- console.error("Error fetching player details:", error);
- playerDetails.push({
- id: player_id,
- imageUrl: "https://cdn.icon-icons.com/icons2/1729/PNG/512/footballjersey12_113031.png"
- });
- }
- }
- }
- const response4 = await axios.get(`http://localhost:3001/events/${gameId}`);
- const events = response4.data;
- for (const event of events) {
- if (event.player_id) {
- event.player_name = await getPlayerName(event.player_id);
- }
- if (event.player_in_id) {
- const playerInId = event.player_in_id.split('.')[0];
- event.player_in_name = await getPlayerName(playerInId);
- }
- if (event.player_assist_id && event.player_assist_id !== '\\N') {
- event.player_assist_name = await getPlayerName(event.player_assist_id);
- }
- }
- // Render the formations data
- res.render('game', { gameData, formazioni, playerDetails, events, lunghezza });
- }
- } catch (error) {
- res.render('error');
- }
- });
- /**
- * Function to get player name.
- *
- * @param {string} playerId - The player's ID.
- * @returns {string} - The player's name.
- */
- async function getPlayerName(playerId) {
- try {
- const playerResponse = await axios.get(`http://localhost:8080/player/${playerId}`);
- const nome = playerResponse.data;
- return nome[0].name;
- } catch (error) {
- console.error(`Error fetching player name with ID ${playerId}:`, error.message);
- return "Unknown"; // Returns an empty string if an error occurs
- }
- }
- /**
- * GET home page.
- *
- * @param {Object} req - The request object.
- * @param {Object} res - The response object.
- * @param {Function} next - The next middleware function.
- */
- router.get('/home', function(req, res, next) {
- res.render('index', { title: 'Soccer Site' });
- });
- /**
- * GET home page.
- *
- * @param {Object} req - The request object.
- * @param {Object} res - The response object.
- * @param {Function} next - The next middleware function.
- */
- router.get('/', function(req, res, next) {
- if (req.session.user) {
- // If the user is logged in, show the preferred team
- const teamId = req.session.user.teamId;
- res.send(`Welcome to the home page! Your favorite team is ${teamId}`);
- } else {
- // If the user is not logged in, show a generic version of the home page
- res.send('Welcome to the home page!');
- }
- res.render('index', { title: 'Soccer Site' });
- });
- /**
- * GET home page.
- *
- * @param {Object} req - The request object.
- * @param {Object} res - The response object.
- * @param {Function} next - The next middleware function.
- */
- router.get('/index', function(req, res, next) {
- res.render('index', { title: 'Soccer Site' });
- });
- /**
- * GET player list page.
- *
- * @param {Object} req - The request object.
- * @param {Object} res - The response object.
- * @param {Function} next - The next middleware function.
- */
- router.get('/player', function(req, res, next) {
- res.render('playerListPage.ejs');
- });
- module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment