Ensure You Have a Player Model:
First, make sure you have a Mongoose model for your Player. If you don't have one yet, you can create it as follows:
// models/Player.js
const mongoose = require('mongoose');
const SocialSchema = new mongoose.Schema({
twitter: { type: String },
facebook: { type: String },
instagram: { type: String },
}, { _id: false });
const PlayerSchema = new mongoose.Schema({
player_id: { type: String, unique: true },
name: { type: String, required: true },
position: { type: String, default: "N/A" },
nationality: { type: String, default: "N/A" },
team: { type: String, default: "N/A" },
league: { type: String, default: "N/A" },
photo_url: { type: String, default: null },
description: { type: String, default: "No description available." },
birthday: { type: String, default: "N/A" },
height: { type: String, default: "N/A" },
weight: { type: String, default: "N/A" },
jerseyNumber: { type: String, default: "N/A" },
social: SocialSchema,
});
module.exports = mongoose.model('Player', PlayerSchema);
Modify the Top Scorers Processing to Include Database Lookup:
Update the section of your controller that processes the top scorers to check the local database for each player. Here's how you can do it:
// controllers/leagueController.js
const axios = require("axios");
const cache = require("../utils/cache"); // Import the cache
const Player = require("../models/Player"); // Import the Player model
/**
* Fetches detailed information about a specific league, its teams, standings, top scorers, and live matches.
* Route: GET /leagues/:code
* Example: GET /leagues/PL
*/
async function leagueController(req, res) {
try {
const leagueCode = req.params.code.toUpperCase(); // Ensure the league code is uppercase (e.g., 'PL')
// Check if the data for this leagueCode is already in the cache
const cachedData = cache.get(leagueCode);
if (cachedData) {
console.log(`Serving cached data for league: ${leagueCode}`);
return res.status(200).json(cachedData);
}
// Define the API endpoints
const leagueInfoUrl = `https://api.football-data.org/v4/competitions/${leagueCode}`;
const leagueTeamsUrl = `https://api.football-data.org/v4/competitions/${leagueCode}/teams`;
// Make parallel API requests for league info and teams using API_FOOTBALL_KEY1
const [leagueResponse, teamsResponse] = await Promise.all([
axios.get(leagueInfoUrl, {
headers: { "X-Auth-Token": process.env.API_FOOTBALL_KEY1 },
}),
axios.get(leagueTeamsUrl, {
headers: { "X-Auth-Token": process.env.API_FOOTBALL_KEY1 },
}),
]);
const leagueData = leagueResponse.data;
const teamsData = teamsResponse.data.teams;
const competitionId = leagueData.id; // Need competition ID for further API calls
// Define endpoints for standings and top scorers using API_FOOTBALL_KEY1
const standingsUrl = `https://api.football-data.org/v4/competitions/${competitionId}/standings`;
const scorersUrl = `https://api.football-data.org/v4/competitions/${leagueCode}/scorers`;
const matchesUrl = `https://api.football-data.org/v4/competitions/${competitionId}/matches`;
// Calculate date range for matches (today to 7 days ahead)
const today = new Date();
const dateFrom = today.toISOString().split("T")[0];
const dateTo = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
.toISOString()
.split("T")[0];
// Make parallel API requests for standings, top scorers, and matches using API_FOOTBALL_KEY1
const [standingsResponse, scorersResponse, matchesResponse] =
await Promise.all([
axios.get(standingsUrl, {
headers: { "X-Auth-Token": process.env.API_FOOTBALL_KEY1 },
}),
axios.get(scorersUrl, {
headers: { "X-Auth-Token": process.env.API_FOOTBALL_KEY1 },
params: {
limit: 10, // Fetch top 10 scorers
},
}),
axios.get(matchesUrl, {
headers: { "X-Auth-Token": process.env.API_FOOTBALL_KEY1 },
params: {
dateFrom,
dateTo,
},
}),
]);
const standingsData = standingsResponse.data;
const scorersData = scorersResponse.data;
const matchesData = matchesResponse.data.matches;
// Process Standings
let standings = [];
if (standingsData.standings && standingsData.standings.length > 0) {
// Assuming the first standing is the overall table
standings = standingsData.standings[0].table.map((team) => ({
position: team.position,
team: {
id: team.team.id,
name: team.team.name,
shortName: team.team.shortName,
tla: team.team.tla,
crest: team.team.crest,
},
playedGames: team.playedGames,
won: team.won,
draw: team.draw,
lost: team.lost,
points: team.points,
goalsFor: team.goalsFor,
goalsAgainst: team.goalsAgainst,
goalDifference: team.goalDifference,
}));
}
// Process Top Scorers with Database Lookup
const topScorers = await Promise.all(
scorersData.scorers.map(async (scorer) => {
// Attempt to find the player in the local database
const localPlayer = await Player.findOne({
name: { $regex: scorer.player.name, $options: "i" },
});
if (localPlayer) {
// Return detailed player information from the local database
return {
player: {
player_id: localPlayer.player_id,
name: localPlayer.name,
position: localPlayer.position,
nationality: localPlayer.nationality,
team: localPlayer.team,
league: localPlayer.league,
photo_url: localPlayer.photo_url,
description: localPlayer.description,
birthday: localPlayer.birthday,
height: localPlayer.height,
weight: localPlayer.weight,
jerseyNumber: localPlayer.jerseyNumber,
social: localPlayer.social,
},
team: {
id: scorer.team.id,
name: scorer.team.name,
shortName: scorer.team.shortName,
tla: scorer.team.tla,
crest: scorer.team.crest,
address: scorer.team.address,
website: scorer.team.website,
founded: scorer.team.founded,
clubColors: scorer.team.clubColors,
venue: scorer.team.venue,
lastUpdated: scorer.team.lastUpdated,
},
goals: scorer.goals,
assists: scorer.assists,
penalties: scorer.penalties,
};
} else {
// Return player information from the external API
return {
player: {
id: scorer.player.id,
name: scorer.player.name,
firstName: scorer.player.firstName,
lastName: scorer.player.lastName,
dateOfBirth: scorer.player.dateOfBirth,
nationality: scorer.player.nationality,
position: scorer.player.position,
shirtNumber: scorer.player.shirtNumber,
lastUpdated: scorer.player.lastUpdated,
},
team: {
id: scorer.team.id,
name: scorer.team.name,
shortName: scorer.team.shortName,
tla: scorer.team.tla,
crest: scorer.team.crest,
address: scorer.team.address,
website: scorer.team.website,
founded: scorer.team.founded,
clubColors: scorer.team.clubColors,
venue: scorer.team.venue,
lastUpdated: scorer.team.lastUpdated,
},
goals: scorer.goals,
assists: scorer.assists,
penalties: scorer.penalties,
};
}
})
);
// Process Matches
const leagueMatchIds = new Set(teamsData.map((team) => team.id));
const matches = matchesData
.filter(
(match) =>
leagueMatchIds.has(match.homeTeam.id) ||
leagueMatchIds.has(match.awayTeam.id)
)
.map((match) => ({
id: match.id,
utcDate: match.utcDate,
status: match.status,
matchday: match.matchday,
stage: match.stage,
group: match.group,
lastUpdated: match.lastUpdated,
homeTeam: {
id: match.homeTeam.id,
name: match.homeTeam.name,
shortName: match.homeTeam.shortName,
tla: match.homeTeam.tla,
crest: match.homeTeam.crest,
},
awayTeam: {
id: match.awayTeam.id,
name: match.awayTeam.name,
shortName: match.awayTeam.shortName,
tla: match.awayTeam.tla,
crest: match.awayTeam.crest,
},
score: match.score,
odds: {
homeWin: Math.random().toFixed(2), // Mock data
draw: Math.random().toFixed(2),
awayWin: Math.random().toFixed(2),
},
}));
// Structure the response
const responseData = {
league: {
id: leagueData.id,
name: leagueData.name,
code: leagueData.code,
type: leagueData.type,
emblem: leagueData.emblem,
area: leagueData.area,
currentSeason: leagueData.currentSeason,
},
teams: teamsData.map((team) => ({
id: team.id,
name: team.name,
shortName: team.shortName,
tla: team.tla,
crest: team.crest,
venue: team.venue,
website: team.website,
founded: team.founded,
clubColors: team.clubColors,
})),
standings,
topScorers,
matches,
};
// Store the response data in the cache
cache.set(leagueCode, responseData);
console.log(`Cached data for league: ${leagueCode}`);
// Send the response
res.status(200).json(responseData);
} catch (error) {
console.error("Error fetching league data:", error.message);
// Handle specific API errors
if (error.response) {
const { status, data } = error.response;
return res.status(status).json({
message: data.message || "Error fetching league data from API.",
});
}
// Generic server error
res.status(500).json({
message: "Unable to retrieve league data. Please try again later.",
});
}
}
module.exports = leagueController;
Example Response Structure:
After these modifications, the topScorers array in your response will contain a mix of data from your local database and the external API based on the availability of player data in your database. Here's an example of how a top scorer entry might look:
{
"player": {
"player_id": "12345",
"name": "John Doe",
"position": "Forward",
"nationality": "Country",
"team": "Team Name",
"league": "PL",
"photo_url": "http://example.com/photo.jpg",
"description": "A talented striker...",
"birthday": "1990-01-01",
"height": "6'0\"",
"weight": "180 lbs",
"jerseyNumber": "9",
"social": {
"twitter": "@johndoe",
"facebook": "johndoe.fb",
"instagram": "@johndoe_ig"
}
},
"team": {
"id": 100,
"name": "Team Name",
"shortName": "TMN",
"tla": "TMN",
"crest": "http://example.com/crest.png",
"address": "123 Stadium Road",
"website": "http://teamwebsite.com",
"founded": 1900,
"clubColors": "Red / White",
"venue": "Stadium Name",
"lastUpdated": "2023-10-01T00:00:00Z"
},
"goals": 20,
"assists": 5,
"penalties": 2
}
Or, if the player is not in your local database:
{
"player": {
"id": "67890",
"name": "Jane Smith",
"firstName": "Jane",
"lastName": "Smith",
"dateOfBirth": "1992-02-02",
"nationality": "Country",
"position": "Midfielder",
"shirtNumber": "8",
"lastUpdated": "2023-10-01T00:00:00Z"
},
"team": {
"id": 101,
"name": "Another Team",
"shortName": "ATM",
"tla": "ATM",
"crest": "http://example.com/another-crest.png",
"address": "456 Another Road",
"website": "http://anotherteam.com",
"founded": 1920,
"clubColors": "Blue / White",
"venue": "Another Stadium",
"lastUpdated": "2023-10-01T00:00:00Z"
},
"goals": 15,
"assists": 7,
"penalties": 1
}