// 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:qoptions: "i" },
}).limit(5);
Assistant
u
er
y
,
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 });
Your playerSearchController.js is quite comprehensive and covers several essential functionalities for searching players, fetching player details, and retrieving recent matches. Below is a detailed review of your code with suggestions for improvements, best practices, and potential optimizations.
1. Code Structure and Organization
Strengths:
Modularization: You've organized your code into separate controller functions, which improves readability and maintainability.
Helper Function: The makeApiRequest utility function centralizes API interactions, reducing repetitive code.
Suggestions:
Use ES6 Modules: Depending on your project setup, consider using ES6 import/export syntax for better readability and tree-shaking capabilities.
Separate Concerns: Consider separating the API interaction logic from the controller logic. This can be achieved by creating a dedicated service layer.
2. Error Handling
Strengths:
Comprehensive Error Handling: Your makeApiRequest function handles various error scenarios, including response errors, request errors, and setup errors.
Consistent Response Structure: You consistently return error messages with appropriate HTTP status codes.
Suggestions:
Use Custom Error Classes: Implement custom error classes to better categorize and manage different error types.
Avoid Leaking Internal Errors: Ensure that internal error messages (e.g., server errors) are not exposed to the client. Instead, send generic error messages and log the detailed errors server-side.
javascript
// Example of using custom error classes
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = "NotFoundError";
this.status = 404;
}
}
// In controller
if (!player) {
throw new NotFoundError("Player not found");
}
// In error handler middleware
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500).json({ error: err.message || "Internal Server Error" });
});
3. Database Operations
Strengths:
Efficient Queries: You're using Mongoose's querying capabilities effectively, with regex for searching and proper indexing assumptions.
Bulk Inserts: Using insertMany with { ordered: false } is efficient for inserting multiple documents while handling duplicates gracefully.
Suggestions:
Indexing: Ensure that fields like player_id and event_id are indexed to optimize query performance, especially for large datasets.
Upsert Operations: Instead of separate find and insert operations, consider using upsert operations (findOneAndUpdate with upsert: true) to streamline database interactions.
javascript
// Example of upsert
await Player.findOneAndUpdate(
{ player_id: playerId },
detailedPlayer,
{ upsert: true, new: true, setDefaultsOnInsert: true }
);
4. API Response Handling
Strengths:
Validation: You validate the structure of the API responses to ensure that the expected data is present before proceeding.
Data Enrichment: You're enriching the API data before storing or returning it, which ensures consistency in your application's data format.
Suggestions:
Pagination Support: Currently, you're limiting results (e.g., .limit(5)), but consider supporting pagination parameters like page and limit to enhance flexibility.
Caching: To reduce redundant API calls and improve performance, implement caching strategies (e.g., using Redis) for frequently accessed data.
5. Logging
Strengths:
Informative Logs: You have detailed logs that provide insights into API responses, database operations, and potential issues.
Suggestions:
Use a Logging Library: Consider using a logging library like Winston or Bunyan for more advanced logging features, such as log levels, transports, and log rotation.
Structured Logging: Implement structured logging (e.g., JSON format) to facilitate easier log parsing and analysis.
javascript
// Example with Winston
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
6. Performance Optimizations
Suggestions:
Batch Requests: If multiple related API calls are needed, consider batching them or using Promise.all to execute them concurrently.
Lazy Loading: For endpoints that might not always require complete data (e.g., player matches), implement lazy loading or partial data fetching to reduce response times.
7. Security Considerations
Suggestions:
Input Validation: Use validation libraries like Joi or express-validator to sanitize and validate incoming request parameters.
javascript
// Example with Joi
const Joi = require('joi');
const searchSchema = Joi.object({
q: Joi.string().min(1).required(),
});
// In controller
const { error, value } = searchSchema.validate(req.query);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
Rate Limiting: Implement rate limiting to prevent abuse of your API endpoints using middleware like express-rate-limit.
Environment Variables: Ensure that sensitive information (e.g., API keys) is stored securely using environment variables and not hard-coded.
8. Code Readability and Maintainability
Suggestions:
Consistent Naming Conventions: Ensure consistent naming for variables and functions. For example, in the API responses, you're using player in some places and players in others.
Documentation: Add JSDoc comments to your functions and important code blocks to improve understandability for future developers.
DRY Principle: Avoid repetition by abstracting commonly used code snippets into reusable functions.
9. Specific Code Improvements
A. Limiting Players in searchPlayers
javascript
// Current code limits to 3 players instead of 5
const limitedPlayers = playersResponse.player.slice(0, 3);
Recommendation: Update the slice to match the comment's intention.
Ensure that the eventslast.php endpoint returns the expected results array. If the structure differs, adjust the response handling accordingly.
C. Repeated API Calls in getPlayerMatches
In the getPlayerMatches function, you fetch player details twice if the player is not found in the local DB. Consider restructuring to minimize API calls.
Optimized Approach:
Fetch Player Details Once: Whether the player exists locally or needs to be fetched, process the player details in a unified way.
Use Caching: Cache the team ID or related data to reduce the need for repeated API calls.
10. Example Refactored Controller Function
Here's how you might refactor the getPlayerDetails function using some of the suggestions mentioned above:
javascript
// controllers/playerSearchController.js
const axios = require("axios");
const Player = require("../models/Player");
const { NotFoundError, BadRequestError } = require("../errors"); // Custom error classes
const logger = require("../utils/logger"); // Winston logger
const baseURL = "https://www.thesportsdb.com/api/v1/json/3";
const makeApiRequest = async (endpoint, params = {}) => {
try {
const response = await axios.get(`${baseURL}/${endpoint}`, { params });
logger.info(`API Response for ${endpoint} with params ${JSON.stringify(params)}`);
return response.data;
} catch (error) {
if (error.response) {
logger.error(`API Error: ${error.response.status} - ${JSON.stringify(error.response.data)}`);
throw new Error(error.response.data.error || "Unknown API error");
} else if (error.request) {
logger.error("No response received from API");
throw new Error("No response received from API");
} else {
logger.error(`Request setup error: ${error.message}`);
throw new Error("Error setting up the API request");
}
}
};
// Example refactored getPlayerDetails
exports.getPlayerDetails = async (req, res, next) => {
const playerId = req.params.id;
if (!playerId) {
return next(new BadRequestError("Player ID is required"));
}
try {
let player = await Player.findOne({ player_id: playerId });
if (!player) {
const playerDetails = await makeApiRequest("lookupplayer.php", { id: playerId });
if (!playerDetails || !playerDetails.players || playerDetails.players.length === 0) {
throw new NotFoundError("Player not found");
}
const playerData = playerDetails.players[0];
const detailedPlayer = {
player_id: playerData.idPlayer,
name: playerData.strPlayer,
// ...other fields
};
player = await Player.findOneAndUpdate(
{ player_id: playerId },
detailedPlayer,
{ upsert: true, new: true, setDefaultsOnInsert: true }
);
logger.info(`Player ID "${playerId}" fetched from API and saved to DB.`);
} else {
logger.info(`Player ID "${playerId}" retrieved from local DB.`);
}
res.json({ status: "success", response: player });
} catch (error) {
logger.error(`Error in getPlayerDetails: ${error.message}`);
next(error); // Pass to global error handler
}
};
11. Additional Enhancements
A. Caching API Responses
Implement caching to store API responses temporarily, reducing the number of external API calls and improving response times.
Your controller is robust and covers critical functionalities required for a player search feature. By implementing the suggestions above, you can enhance the performance, security, and maintainability of your application. Always ensure to follow best practices and keep scalability in mind as your application grows.
If you have specific areas you'd like to focus on or encounter any issues, feel free to ask for more targeted assistance!