// Helper function to make API requests
const makeApiRequest = async (endpoint, params = {}) => {
try {
const response = await axios.get(${baseURL}/${endpoint}, { params });
console.log(API Response for ${endpoint} with params ${JSON.stringify(params)}:, response.data);
return response.data;
} catch (error) {
if (error.response) {
console.error(
API Error: ${error.response.status} - ${JSON.stringify( error.response.data )}
);
throw new Error(
API Error: ${error.response.data.error || "Unknown error"}
);
} else if (error.request) {
console.error("No response received from API");
throw new Error("No response received from API");
} else {
console.error("Error setting up the request:", error.message);
throw new Error("Error setting up the request");
}
}
};
/**
Search for players by name directly using the new V1 API.
Returns up to 5 matching players.
*/
exports.searchPlayers = async (req, res) => {
const query = req.query.q;
if (!query) {
return res.status(400).json({ error: "Search query 'q' is required" });
}
try {
// Search in the local database first
const localPlayers = await Player.find({
name: { regex:query,options: "i" },
}).limit(5);
code
if (localPlayers.length > 0) {
return res.json({ count: localPlayers.length, players: localPlayers });
}
// If not found locally, fetch from API
const playersResponse = await makeApiRequest("searchplayers.php", {
p: query,
});
// Validate response structure
if (
!playersResponse ||
!playersResponse.player ||
!Array.isArray(playersResponse.player)
) {
return res
.status(404)
.json({ error: "No players found matching the query" });
}
// Limit to 5 players
const limitedPlayers = playersResponse.player.slice(0, 3);
// Enrich player data with necessary fields
const enrichedPlayers = limitedPlayers.map((player) => ({
player_id: player.idPlayer,
name: player.strPlayer,
position: player.strPosition || "N/A",
nationality: player.strNationality || "N/A",
team: player.strTeam || "N/A",
league: player.strLeague || "N/A",
photo_url: player.strThumb || null,
description: player.strDescriptionEN || "No description available.",
birthday: player.dateBorn || "N/A",
height: player.strHeight || "N/A",
weight: player.strWeight || "N/A",
jerseyNumber: player.strNumber || "N/A",
social: {
twitter: player.strTwitter || null,
facebook: player.strFacebook || null,
instagram: player.strInstagram || null,
},
}));
// Save fetched players to the local database
await Player.insertMany(
enrichedPlayers,
{ ordered: false } // Continue on duplicate errors
).catch((err) => {
if (err.code === 11000) {
console.warn("Duplicate player entries detected.");
} else {
console.error("Error inserting players into DB:", err.message);
}
});
res.json({ count: enrichedPlayers.length, players: enrichedPlayers });
Get detailed information about a specific player by ID using the new V1 API.
*/
exports.getPlayerDetails = async (req, res) => {
const playerId = req.params.id;
if (!playerId) {
return res.status(400).json({ error: "Player ID is required" });
}
try {
// Check local DB first
const localPlayer = await Player.findOne({ player_id: playerId });
code
if (localPlayer) {
console.log(`Player ID "${playerId}" found in local DB.`);
return res.json({ status: "success", response: localPlayer });
}
console.log(
`Player ID "${playerId}" not found in local DB. Fetching from API.`
);
// If not found locally, fetch from API
const playerDetailsResponse = await makeApiRequest("lookupplayer.php", {
id: playerId,
});
// Validate response structure
if (
!playerDetailsResponse ||
playerDetailsResponse.players === null ||
!Array.isArray(playerDetailsResponse.players) ||
playerDetailsResponse.players.length === 0
) {
console.warn(`API returned no data for Player ID "${playerId}".`);
return res.status(404).json({ error: "Player not found" });
}
const player = playerDetailsResponse.players[0];
// Structure the player details
const detailedPlayer = {
player_id: player.idPlayer,
name: player.strPlayer,
position: player.strPosition || "N/A",
nationality: player.strNationality || "N/A",
team: player.strTeam || "N/A",
league: player.strLeague || "N/A",
photo_url: player.strThumb || null,
description: player.strDescriptionEN || "No description available.",
birthday: player.dateBorn || "N/A",
height: player.strHeight || "N/A",
weight: player.strWeight || "N/A",
jerseyNumber: player.strNumber || "N/A",
social: {
twitter: player.strTwitter || null,
facebook: player.strFacebook || null,
instagram: player.strInstagram || null,
},
};
console.log(`Fetched player details for Player ID "${playerId}" from API.`);
// Save to local DB
try {
await Player.create(detailedPlayer);
console.log(`Player ID "${playerId}" saved to local DB.`);
} catch (err) {
if (err.code === 11000) {
console.warn(`Player ID "${playerId}" already exists in the database.`);
} else {
console.error("Error inserting player into DB:", err.message);
}
}
res.json({ status: "success", response: detailedPlayer });
Get recent matches/events for a specific player using the new V1 API.
This example assumes that you have stored matches in your local DB.
*/
exports.getPlayerMatches = async (req, res) => {
const playerId = req.params.id;
const limit = parseInt(req.query.limit) || 5;
if (!playerId) {
return res.status(400).json({ error: "Player ID is required" });
}
try {
// Check if the player exists in the database
const player = await Player.findOne({ player_id: playerId });
if (!player) {
console.log(
Player ID "${playerId}" not found in local DB. Fetching player details to proceed.
);
// Attempt to fetch player details from API
const playerDetailsResponse = await makeApiRequest("lookupplayer.php", {
id: playerId,
});
code
// Validate response structure
if (
!playerDetailsResponse ||
playerDetailsResponse.players === null ||
!Array.isArray(playerDetailsResponse.players) ||
playerDetailsResponse.players.length === 0
) {
console.warn(`API returned no data for Player ID "${playerId}".`);
return res.status(404).json({ error: "Player not found" });
}
const playerData = playerDetailsResponse.players[0];
// Structure the player details
const detailedPlayer = {
player_id: playerData.idPlayer,
name: playerData.strPlayer,
position: playerData.strPosition || "N/A",
nationality: playerData.strNationality || "N/A",
team: playerData.strTeam || "N/A",
league: playerData.strLeague || "N/A",
photo_url: playerData.strThumb || null,
description: playerData.strDescriptionEN || "No description available.",
birthday: playerData.dateBorn || "N/A",
height: playerData.strHeight || "N/A",
weight: playerData.strWeight || "N/A",
jerseyNumber: playerData.strNumber || "N/A",
social: {
twitter: playerData.strTwitter || null,
facebook: playerData.strFacebook || null,
instagram: playerData.strInstagram || null,
},
};
// Save to local DB
try {
await Player.create(detailedPlayer);
console.log(`Player ID "${playerId}" saved to local DB.`);
} catch (err) {
if (err.code === 11000) {
console.warn(
`Player ID "${playerId}" already exists in the database.`
);
} else {
console.error("Error inserting player into DB:", err.message);
}
}
} else {
console.log(`Player ID "${playerId}" found in local DB.`);
}
// Now that the player exists in the database, fetch matches
// Check local DB for matches
const localMatches = await Match.find({ player_id: playerId })
.sort({ date: -1 })
.limit(limit);
if (localMatches.length >= limit) {
console.log(
`Found ${localMatches.length} matches in local DB for Player ID "${playerId}".`
);
return res.json({
count: localMatches.length,
matches: localMatches,
});
}
console.log(
`Found only ${localMatches.length} matches in local DB for Player ID "${playerId}". Fetching additional matches from API.`
);
// Fetch player details to get the team ID
const playerDetailsResponse = await makeApiRequest("lookupplayer.php", {
id: playerId,
});
if (
!playerDetailsResponse ||
playerDetailsResponse.players === null ||
!Array.isArray(playerDetailsResponse.players) ||
playerDetailsResponse.players.length === 0
) {
throw new Error("Player not found");
}
const playerData = playerDetailsResponse.players[0];
const teamId = playerData.idTeam;
if (!teamId) {
throw new Error("Team ID not available for this player");
}
// Fetch recent events for the team
const eventsResponse = await makeApiRequest("eventslast.php", {
id: teamId,
});
if (
!eventsResponse ||
!eventsResponse.results ||
!Array.isArray(eventsResponse.results)
) {
throw new Error("No events found for the player's team");
}
// Structure the match details
const matches = eventsResponse.results
.slice(0, limit - localMatches.length)
.map((event) => ({
event_id: event.idEvent,
league: event.strLeague,
season: event.strSeason,
date: event.dateEvent,
time: event.strTime,
homeTeam: event.strHomeTeam,
awayTeam: event.strAwayTeam,
homeScore: event.intHomeScore,
awayScore: event.intAwayScore,
status: event.strStatus,
player_id: playerId,
fetchedAt: new Date(),
}));
console.log(
`Fetched ${matches.length} new matches from API for Player ID "${playerId}".`
);
// Save new matches to local DB
await Match.insertMany(
matches,
{ ordered: false } // Continue on duplicate errors
).catch((err) => {
if (err.code === 11000) {
console.warn("Duplicate match entries detected.");
} else {
console.error("Error inserting matches into DB:", err.message);
}
});
// Combine local and newly fetched matches
const combinedMatches = [...localMatches, ...matches].slice(0, limit);
console.log(
`Returning ${combinedMatches.length} matches for Player ID "${playerId}".`
);
res.json({ count: combinedMatches.length, matches: combinedMatches });
I'm sorry to hear you're encountering issues with the player search functionality in your FootballBuzz application. Let's systematically diagnose and address the problem to ensure that the player search feature works as expected.
1. Overview of the Search Flow
To understand where the issue might be, let's break down the flow of the player search functionality:
Frontend (Next.js):
Component:PlayerSearch.tsx triggers a search when the user inputs a query.
API Call: It uses the searchPlayers function from utils/api.ts to call the backend API.
UI Update: Based on the response, it updates the state and displays the search results.
Backend (Express.js):
Route:/api/searchPlayers handles the search requests.
Controller:playerSearchController.js processes the search by querying the local database or fetching from TheSportsDB API.
Database: Stores player information to optimize future searches.
2. Potential Issues and Solutions
Let's explore potential reasons why the search functionality isn't working and how to resolve them.
A. Backend Server Not Running or Misconfigured
Issue:
The backend server might not be running, or the API routes may not be correctly set up, making the /api/searchPlayers endpoint inaccessible.
Solution:
Ensure Backend Server is Running:
Verify that your backend Express server is running on localhost:5000.
You can start the server using a command like node server.js or npm start depending on your setup.
Verify Route Registration:
Ensure that the playerRoutes.js is correctly registered in your main server file (e.g., server.js or app.js).
javascript
// server.js or app.js
const express = require('express');
const cors = require('cors'); // Import CORS middleware
const playerRoutes = require('./routes/playerRoutes');
const app = express();
// Middleware
app.use(cors()); // Enable CORS
app.use(express.json());
// Register Routes
app.use('/api', playerRoutes);
// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Restart the Server:
After making changes, restart your backend server to apply them.
B. CORS (Cross-Origin Resource Sharing) Issues
Issue:
If your frontend and backend are on different origins (e.g., localhost:3000 for Next.js and localhost:5000 for Express), CORS policies might block the requests.
Solution:
Enable CORS in Express:
Ensure you've installed the cors package:
bash
npm install cors
Enable CORS in your main server file:
javascript
const cors = require('cors');
app.use(cors({
origin: 'http://localhost:3000', // Replace with your frontend's origin
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true,
}));
Verify Frontend Requests:
Ensure that your frontend is making requests to the correct backend origin.
C. Incorrect API Base URL in Frontend
Issue:
The frontend might be pointing to an incorrect API base URL, causing the requests to fail.
Solution:
Check .env.local File:
Ensure that the NEXT_PUBLIC_API_BASE_URL is correctly set in your .env.local file.
In playerSearchController.js, you already handle duplicate player entries with ordered: false. Ensure that the database enforces uniqueness on player_id to prevent duplicates.
javascript
await Player.insertMany(
enrichedPlayers,
{ ordered: false }
).catch((err) => {
if (err.code === 11000) {
console.warn("Duplicate player entries detected.");
} else {
console.error("Error inserting players into DB:", err.message);
}
});
3. Step-by-Step Debugging Guide
To identify and resolve the issue, follow these steps:
Step 1: Verify Backend Accessibility
Test API Endpoint:
Open your browser and navigate to http://localhost:5000/api/searchPlayers?q=Messi.
You should receive a JSON response with player data or an appropriate error message.
Handle No Response or Errors:
If you don’t get a response or encounter errors, check the backend server logs for clues.
Step 2: Check Frontend API Calls
Inspect Network Requests:
Open your browser's Developer Tools (F12 or right-click → Inspect).
Navigate to the Network tab.
Perform a player search and observe the network requests.
Ensure that the request to /api/searchPlayers is successful (status code 200).
Identify Failed Requests:
If the request fails (e.g., status code 500), note the error message.
Step 3: Review Console Logs
Frontend Console:
Look for any errors or warnings in the browser console that might indicate issues with API calls or component rendering.
Backend Console:
Observe the backend server console for any runtime errors or logs indicating failed operations.
Step 4: Validate Environment Variables
Ensure Correct .env.local:
Confirm that NEXT_PUBLIC_API_BASE_URL is correctly set to http://localhost:5000/api.
Restart Servers:
After updating environment variables, restart both frontend and backend servers to apply changes.
Step 5: Test API Independently
Use Postman or cURL:
Send a GET request to http://localhost:5000/api/searchPlayers?q=Messi.
Ensure that sensitive information (like API keys) are not exposed in the frontend. Only variables prefixed with NEXT_PUBLIC_ are accessible on the client side.
Implement Loading Indicators:
Enhance user experience by showing loading spinners or indicators during API calls.
Handle Edge Cases:
Manage scenarios where the external API returns incomplete data or unexpected structures.
Optimize Database Queries:
Use indexing on frequently searched fields like name to improve query performance.
Deploy with Proper Configuration:
When deploying, ensure that environment variables are correctly set and that CORS policies are appropriately configured to allow legitimate requests.
5. Conclusion
By methodically verifying each part of the search functionality—from frontend API calls to backend route handling and database interactions—you can identify and resolve the issue preventing player searches. Start by ensuring that your backend server is running correctly and that the API endpoints are accessible. Utilize debugging tools like browser developer consoles and Postman to test API responses. Enhancing error handling and logging will provide more visibility into potential issues, facilitating quicker resolutions.
If after following these steps you still encounter issues, please provide specific error messages or behaviors you're observing. This will allow for more targeted assistance.