From 24e03f954b1c4478d813c9b077e26dfe45742b65 Mon Sep 17 00:00:00 2001 From: Erik Date: Thu, 27 Nov 2025 12:55:31 -0300 Subject: [PATCH] fix: adicionar timeout e logs na traducao --- frontend/src/app/api/pages/[slug]/route.ts | 26 +++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/frontend/src/app/api/pages/[slug]/route.ts b/frontend/src/app/api/pages/[slug]/route.ts index e70ac4a..a901992 100644 --- a/frontend/src/app/api/pages/[slug]/route.ts +++ b/frontend/src/app/api/pages/[slug]/route.ts @@ -29,10 +29,11 @@ async function authenticate() { } } -// Tradução com cache +// Tradução com cache e timeout async function translateText(text: string, targetLang: string): Promise { if (!text || text.trim() === '' || targetLang === 'pt') return text; + // Buscar do cache primeiro try { const cached = await prisma.translation.findUnique({ where: { @@ -51,17 +52,27 @@ async function translateText(text: string, targetLang: string): Promise console.error('[i18n] Erro ao buscar cache de tradução:', error); } + // Traduzir via LibreTranslate com timeout de 30s try { + console.log(`[i18n] Traduzindo "${text.substring(0, 50)}..." para ${targetLang}`); + + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 30000); + const response = await fetch(`${LIBRETRANSLATE_URL}/translate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ q: text, source: 'pt', target: targetLang, format: 'text' }), + signal: controller.signal }); + clearTimeout(timeoutId); + if (response.ok) { const data = await response.json(); const translatedText = data.translatedText || text; + // Salvar no cache try { await prisma.translation.create({ data: { @@ -72,13 +83,22 @@ async function translateText(text: string, targetLang: string): Promise } }); } catch (cacheError) { - console.warn('[i18n] Falha ao salvar cache de tradução:', cacheError); + // Ignorar erro de duplicata + if (!(cacheError instanceof Error && cacheError.message.includes('Unique constraint'))) { + console.warn('[i18n] Falha ao salvar cache de tradução:', cacheError); + } } return translatedText; + } else { + console.error(`[i18n] LibreTranslate retornou status ${response.status}`); } } catch (error) { - console.error(`[i18n] Erro ao traduzir texto para ${targetLang}:`, error); + if (error instanceof Error && error.name === 'AbortError') { + console.error(`[i18n] Timeout ao traduzir para ${targetLang} (30s)`); + } else { + console.error(`[i18n] Erro ao traduzir texto para ${targetLang}:`, error); + } } return text;