-
Notifications
You must be signed in to change notification settings - Fork 9
/
translator.js
54 lines (43 loc) · 1.34 KB
/
translator.js
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
'use strict';
const fs = require.main.require("fs");
const LANGUAGE_DIR = __dirname + '/public/languages/';
let languages, texts = null;
function replaceParams(message, params) {
if (!params) return message;
return message.replace(/%(\d+)/gi, (match, captured) => { return params[captured]; });
}
function languageSupported(language) {
return languages.indexOf(language) !== -1;
}
let translator = {
translate(text, params, language, defaultLanguage) {
if (!languageSupported(language)) {
language = defaultLanguage || 'en_GB';
}
if (texts[language][text]) {
return replaceParams(texts[language][text], params);
} else {
return text;
}
}
};
function loadLanguageTexts(language) {
let allPhrases = {};
fs.readdirSync(LANGUAGE_DIR + language).forEach(function (phrasesFile) {
let phrases = require(LANGUAGE_DIR + language + '/' + phrasesFile);
for (let phraseKey in phrases) {
allPhrases[phraseKey] = phrases[phraseKey];
}
});
return allPhrases;
}
function loadTexts() {
languages = [];
texts = [];
fs.readdirSync(LANGUAGE_DIR).forEach(function (langFolder) {
languages.push(langFolder);
texts[langFolder] = loadLanguageTexts(langFolder);
});
}
loadTexts();
module.exports = translator;