1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
import translateGoogle from 'google-translate-api-x';
import { LIVE_API_FERDIUM_LIBRETRANSLATE } from '../config';
export async function translateTo(
text: string,
translateToLanguage: string,
translatorEngine: string,
): Promise<{ text: string; error: boolean }> {
const errorText =
// TODO: Need to support i18n
'FERDIUM ERROR: An error occured. Please select less text to translate or try again later.';
if (translatorEngine === 'Google') {
const translationResult = await translateGoogle(text, {
to: translateToLanguage,
autoCorrect: true,
})
.then(res => ({ text: res.text, error: false }))
.catch(() => ({ text: errorText, error: true }));
return translationResult;
}
if (translatorEngine === 'LibreTranslate') {
try {
const res = await fetch(LIVE_API_FERDIUM_LIBRETRANSLATE, {
method: 'POST',
body: JSON.stringify({
q: text,
source: 'auto',
target: translateToLanguage,
}),
headers: {
'Content-Type': 'application/json',
},
});
const response = await res.json();
return { text: response.translatedText, error: false };
} catch {
return { text: errorText, error: true };
}
}
return { text: errorText, error: true };
}
|