fix: adicionar timeout e logs na traducao
This commit is contained in:
@@ -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<string> {
|
||||
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<string>
|
||||
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,14 +83,23 @@ async function translateText(text: string, targetLang: string): Promise<string>
|
||||
}
|
||||
});
|
||||
} catch (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) {
|
||||
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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user