-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (66 loc) · 2.69 KB
/
index.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
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
const fs = require('fs');
const appRootDir = require('app-root-dir');
const arrayUtils = require('./utils/arrayUtils');
class Translate {
/**
*
* @param {String} locale : local code to load, ex : 'fr-fr'. If not found, default locale is loaded
*/
_loadLocaleFile(locale) {
let locales = {};
try {
locales = require(`${this.localesDir}/${locale}.json`);
}catch(error) {
console.warn(`Failed to load locale file : ${locale}.json. Loading default file : ${this.defaultLocale}`)
//console.warn(error);
locales = require(`${this.localesDir}/${this.defaultLocale}.json`);
}
return locales;
}
constructor() {
this.localesDir = appRootDir.get()+'/locales';
this.defaultLocale = "fr-fr";
}
/**
*
* @param {Object} configuration : default_locale to update default locale
*
*/
config(configuration) {
if(!configuration) return;
if(configuration.default_locale) {
if(fs.existsSync(`${this.localesDir}/${configuration.default_locale}.json`))
this.defaultLocale = configuration.default_locale;
else
console.warn(`${configuration.default_locale}.json does not exist !`)
}
if(configuration.locales_directory) {
const _dir = appRootDir.get()+'/'+configuration.locales_directory;
if(fs.existsSync(_dir) && fs.existsSync(`${_dir}/${this.defaultLocale}.json`))
this.localesDir = _dir;
else
console.warn(`${_dir} is not valid. Directory does not exist, or does not contains any json file`)
}
}
init(locale) {
const lang = locale.indexOf('-')!==-1?locale:`${locale}-${locale}`;
const locales = this._loadLocaleFile(lang);
return (key, params) => {
if(!locales || Object.keys(locales).length === 0)
throw new Error('Error : locales were not loaded correctly. Please use module.config({"locales_directory":"locales/json/files/" to a correct directory.}')
const value = locales[key];
let output = "";
if(!value) return key;
else if (!Array.isArray(value)) output=value;
else output=arrayUtils.shuffle(value)[0];
if(!params) return output;
const keys = Object.keys(params);
keys.forEach(paramKey => {
while(output.indexOf(`{{${paramKey}}}`) !== -1)
output = output.replace(`{{${paramKey}}}`,params[paramKey]);
})
return output;
};
}
}
module.exports = new Translate();