UNPKG

2.83 kBJavaScriptView Raw
1const axios = require("axios");
2
3/**
4 * Tests whether the given variable is a real object and not an Array
5 * @param {any} it The variable to test
6 * @returns {it is Record<string, any>}
7 */
8function isObject(it) {
9 // This is necessary because:
10 // typeof null === 'object'
11 // typeof [] === 'object'
12 // [] instanceof Object === true
13 return Object.prototype.toString.call(it) === "[object Object]";
14}
15
16/**
17 * Tests whether the given variable is really an Array
18 * @param {any} it The variable to test
19 * @returns {it is any[]}
20 */
21function isArray(it) {
22 if (Array.isArray != null)
23 return Array.isArray(it);
24 return Object.prototype.toString.call(it) === "[object Array]";
25}
26
27/**
28 * Choose the right tranalation API
29 * @param {string} text The text to translate
30 * @param {string} targetLang The target languate
31 * @param {string} yandex api key
32 * @returns {Promise<string>}
33 */
34async function translateText(text, targetLang, yandex) {
35 if (targetLang === "en") {
36 return text;
37 }
38 if (yandex) {
39 return await translateYandex(text, targetLang, yandex);
40 } else {
41 return await translateGoogle(text, targetLang);
42 }
43}
44
45/**
46 * Translates text with Yandex API
47 * @param {string} text The text to translate
48 * @param {string} targetLang The target languate
49 * @param {string} yandex api key
50 * @returns {Promise<string>}
51 */
52async function translateYandex(text, targetLang, yandex) {
53 if (targetLang === "zh-cn") {
54 targetLang = "zh";
55 }
56 try {
57 const url = `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${yandex}&text=${encodeURIComponent(text)}&lang=en-${targetLang}`;
58 const response = await axios({url, timeout: 15000});
59 if (response.data && response.data['text']) {
60 return response.data['text'][0];
61 }
62 throw new Error("Invalid response for translate request");
63 } catch (e) {
64 throw new Error(`Could not translate to "${targetLang}": ${e}`);
65 }
66}
67
68/**
69 * Translates text with Google API
70 * @param {string} text The text to translate
71 * @param {string} targetLang The target languate
72 * @returns {Promise<string>}
73 */
74async function translateGoogle(text, targetLang) {
75 try {
76 const url = `http://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}&ie=UTF-8&oe=UTF-8`;
77 const response = await axios({url, timeout: 15000});
78 if (isArray(response.data)) {
79 // we got a valid response
80 return response.data[0][0][0];
81 }
82 throw new Error("Invalid response for translate request");
83 } catch (e) {
84 throw new Error(`Could not translate to "${targetLang}": ${e}`);
85 }
86}
87
88module.exports = {
89 isArray,
90 isObject,
91 translateText
92};
\No newline at end of file