-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-i18n.js
77 lines (69 loc) · 1.98 KB
/
server-i18n.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
import get from 'lodash.get';
let i18nJson = {};
let defaultLang = false;
// eslint-disable-next-line
export const ServerI18n = {
/**
* Initializes the object with the given translation json (as string)
* @param {string} i18nText The i18n string.
* @throws JSONError
*/
init(i18nText) {
i18nJson = JSON.parse(i18nText);
},
/**
* Returns all initialized languages.
*/
getLanguages() {
return Object.keys(i18nJson);
},
/**
* Sets a default lang which will be used if the specified lang
* was not initialized.
* @param {string} lang The language to default to.
*/
setDefaultLang(lang) {
defaultLang = lang;
},
/**
* Translates a given key for a given language. Uses the default
* lang if the lang given is not initialized and the default lang
* was set via setDefaultLang.
* @param {string} key The translation key
* @param {string} lang The language to translate to
* @param {string | string[]} sprintf The replacements for '%s'
* @throws Error if the language is not initalized and
*/
__(key, lang, sprintf) {
let langToUse = lang;
if (!i18nJson || !i18nJson[langToUse]) {
if (!defaultLang) {
throw new Error('not initialized');
} else {
langToUse = defaultLang;
}
}
let value = get(i18nJson[langToUse], key, key);
if (sprintf) {
const workingArr = Array.isArray(sprintf) ? sprintf : [sprintf];
for (let i = 0; i < workingArr.length; i += 1) {
value = value.replace('%s', workingArr[i]);
}
}
return value;
},
/**
* Returns a translation function for using with SSR for example.
* @param {string} lang The language to be used in the translations.
* @returns {Function} The translation function (key, ...sprintfArgs)
*/
ssrTranslation(lang) {
return (key, ...args) => {
let sprintf = false;
if (args && args.length > 0) {
sprintf = args;
}
return ServerI18n.__(key, lang, sprintf);
};
},
};