UNPKG

bhashantarh

Version:

Tiny translation wrapper with fallbacks (LibreTranslate -> MyMemory) and detection with franc fallback.

44 lines (37 loc) 1.17 kB
const axios = require('axios'); const FALLBACK_URL = 'https://libretranslate.de'; // MyMemory fallback async function tryMyMemory(text, from, to) { const url = 'https://api.mymemory.translated.net/get'; const res = await axios.get(url, { params: { q: text, langpair: `${from}|${to}` }, timeout: 8000 }); return res.data?.responseData?.translatedText || null; } async function tryLibreTranslate(text, from, to) { const body = { q: text, source: from, target: to, format: 'text' }; const res = await axios.post(`${FALLBACK_URL}/translate`, body, { headers: { 'Content-Type': 'application/json' }, timeout: 10000 }); return res.data?.translatedText || null; } async function translate(text, from, to) { // 1) LibreTranslate.de try { const t1 = await tryLibreTranslate(text, from, to); if (t1) return t1; } catch (err) { console.error('LibreTranslate.de translate error:', err.message); } // 2) MyMemory try { const t2 = await tryMyMemory(text, from, to); if (t2) return t2; } catch (err) { console.error('MyMemory translate error:', err.message); } return null; } module.exports = translate;