/
google-translate.ts
90 lines (76 loc) · 2.34 KB
/
google-translate.ts
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { v2 } from '@google-cloud/translate';
import { decode } from 'html-entities';
import {
replaceInterpolations,
reInsertInterpolations,
Matcher,
} from '../matchers';
import { TranslationService, TString } from '.';
// Contains replacements for language codes
const codeMap = {
'zh-tw': 'zh-TW',
};
export class GoogleTranslate implements TranslationService {
private translate: v2.Translate;
private interpolationMatcher: Matcher;
private supportedLanguages: string[] = [];
private decodeEscapes: boolean;
public name = 'Google Translate';
cleanResponse(response: string) {
const translated = response.replace(
/\<(.+?)\s*\>\s*(.+?)\s*\<\/\s*(.+?)>/g,
'<$1>$2</$3>',
);
return this.decodeEscapes ? decode(translated) : translated;
}
async initialize(
config?: string,
interpolationMatcher?: Matcher,
decodeEscapes?: boolean,
) {
this.translate = new v2.Translate({
autoRetry: true,
keyFilename: config || undefined,
});
this.interpolationMatcher = interpolationMatcher;
this.supportedLanguages = await this.getAvailableLanguages();
this.decodeEscapes = decodeEscapes;
}
async getAvailableLanguages() {
const [languages] = await this.translate.getLanguages();
console.log(languages);
return languages.map((l) => l.code.toLowerCase());
}
supportsLanguage(language: string) {
return this.supportedLanguages.includes(language);
}
cleanLanguageCode(languageCode: string) {
const lowerCaseCode = languageCode.toLowerCase();
console.log('Lower case:', languageCode);
if (codeMap[lowerCaseCode]) {
return codeMap[lowerCaseCode];
}
return lowerCaseCode.split('-')[0];
}
async translateStrings(strings: TString[], from: string, to: string) {
return Promise.all(
strings.map(async ({ key, value }) => {
const { clean, replacements } = replaceInterpolations(
value,
this.interpolationMatcher,
);
const [translationResult] = await this.translate.translate(clean, {
from: this.cleanLanguageCode(from),
to: this.cleanLanguageCode(to),
});
return {
key: key,
value: value,
translated: this.cleanResponse(
reInsertInterpolations(translationResult, replacements),
),
};
}),
);
}
}