aboutsummaryrefslogtreecommitdiffstats
path: root/src/helpers/translation-helpers.ts
blob: 215b2a49c7873ec3b8f1f9713613b851fcb2094a (plain) (blame)
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 fetch from 'node-fetch';
import translateGoogle from 'translate-google';
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') {
    try {
      const res = await translateGoogle(text, {
        to: translateToLanguage,
      });

      return { text: res, error: false };
    } catch {
      return { text: errorText, error: true };
    }
  } else 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 };
}