From ee23f61057c6c85a6d2a795c8688f9e5167ca09d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoni=20Nu=C3=B1ez=20Romeu?= Date: Mon, 13 Jul 2026 16:23:07 +0200 Subject: [PATCH] fix(backend): improve OFF API error handling - Validate response is JSON before parsing (OFF returns HTML on 503) - Don't cache empty results to avoid blocking future searches - Add validateStatus to only accept 200 responses - Better logging for API failures --- apps/backend/off-service.js | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/apps/backend/off-service.js b/apps/backend/off-service.js index e7e28c7..9c5a3bd 100644 --- a/apps/backend/off-service.js +++ b/apps/backend/off-service.js @@ -62,23 +62,31 @@ export async function searchBabyProducts(query) { action: 'process', }, timeout: 10000, + validateStatus: (status) => status === 200, }); - if (response.data && response.data.products) { - const products = response.data.products - .map(transformOFFProduct) - .filter(Boolean); + // Check if response is actually JSON (OFF sometimes returns HTML on error) + if (typeof response.data === 'string' || !response.data.products) { + console.warn(`[OFF] Invalid response for "${searchTerm}": API may be down`); + return []; + } + const products = response.data.products + .map(transformOFFProduct) + .filter(Boolean); + + // Only cache non-empty results to avoid caching API failures + if (products.length > 0) { try { await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(products)); console.log(`Cached ${products.length} OFF products for: ${searchTerm}`); } catch (cacheErr) { // cache write failed, still return the data } - return products; + } else { + console.log(`[OFF] No products found for "${searchTerm}", not caching empty result`); } - - return []; + return products; } catch (error) { console.error('Error searching baby products from OFF:', error.message); return [];