diff --git a/src/app/evalbars/App.js b/src/app/evalbars/App.js index ad77d93..b51d1b0 100644 --- a/src/app/evalbars/App.js +++ b/src/app/evalbars/App.js @@ -149,48 +149,42 @@ function App() { } }; + // Cache to prevent duplicate API calls + const evalCacheRef = useRef(new Map()); + const fetchEvaluation = async (fen) => { - // Encode the FEN string to be safely included in a URL - const encodedFen = encodeURIComponent(fen); - const endpoint = `https://eval.plc.hadron43.in/eval-bars/?fen=${encodedFen}`; + // Check cache first to avoid duplicate calls + if (evalCacheRef.current.has(fen)) { + return evalCacheRef.current.get(fen); + } try { - const response = await fetch(endpoint, { - method: 'GET', // Changed to GET as the new API uses URL parameters - headers: { - // 'Content-Type': 'application/json', // Not strictly necessary for a GET request without a body - // You might need other headers depending on the API requirements, like an API key. - }, - // body: JSON.stringify({ fen }), // Removed as FEN is now in the URL - }); + const encodedFen = encodeURIComponent(fen); + const response = await fetch(`https://eval.plc.hadron43.in/eval-bars/?fen=${encodedFen}`); if (!response.ok) { - // Attempt to get more error information from the response if available - let errorMessage = `Network response was not ok (status: ${response.status})`; - try { - const errorData = await response.json(); - errorMessage += ` - ${errorData.message || JSON.stringify(errorData)}`; - } catch (e) { - // If response is not JSON or another error occurs - errorMessage += ` - ${response.statusText}`; - } - throw new Error(errorMessage); + throw new Error(`API failed: ${response.status}`); } const data = await response.json(); - - // The new API returns an object like {"evaluation": 7.04} - // It does not provide 'bestMove'. - return { + const result = { evaluation: data.evaluation, - bestMove: null, // Set to null or undefined as the new API doesn't provide it - // Note: This API doesn't provide mate, ponder, continuation, or bestMove information + bestMove: null, }; + + // Cache the result + evalCacheRef.current.set(fen, result); + + // Limit cache size to prevent memory issues (keep last 500 positions) + if (evalCacheRef.current.size > 500) { + const firstKey = evalCacheRef.current.keys().next().value; + evalCacheRef.current.delete(firstKey); + } + + return result; } catch (error) { - console.error("Failed to fetch evaluation:", error); - // Depending on how you want to handle errors, you might re-throw, - // return a default/error object, or handle it directly. - throw error; // Re-throwing the error to be caught by the caller + console.error('API failed:', error.message); + throw error; } }; const handleRemoveLink = (index) => {