-
Notifications
You must be signed in to change notification settings - Fork 3k
/
translate.js
59 lines (51 loc) · 2.01 KB
/
translate.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
import lodashGet from 'lodash/get';
import Str from 'expensify-common/lib/str';
import Log from './Log';
import Config from '../CONFIG';
import translations from '../languages/translations';
/**
* Return translated string for given locale and phrase
*
* @param {String} locale eg 'en', 'es-ES'
* @param {String|Array} phrase
* @param {Object} variables
* @returns {string}
*/
function translate(locale, phrase, variables = {}) {
const localeLanguage = locale.substring(0, 2);
const fullLocale = lodashGet(translations, locale, {});
const language = lodashGet(translations, localeLanguage, {});
const defaultLanguage = lodashGet(translations, 'en', {});
let translationValue;
// Search phrase in full locale
translationValue = lodashGet(fullLocale, phrase);
if (translationValue) {
return Str.result(translationValue, variables);
}
// Phrase is not found in full locale, search it in language
translationValue = lodashGet(language, phrase);
if (translationValue) {
return Str.result(translationValue, variables);
}
if (localeLanguage !== 'en') {
Log.alert(`${phrase} was not found in the ${localeLanguage} locale`, 0, {}, false);
}
// Phrase is not translated, search it in default language (en)
translationValue = lodashGet(defaultLanguage, phrase);
if (translationValue) {
return Str.result(translationValue, variables);
}
// Phrase is not found in default language, on production log an alert to server
// on development throw an error
if (Config.IS_IN_PRODUCTION) {
const phraseString = Array.isArray(phrase) ? phrase.join('.') : phrase;
Log.alert(`${phraseString} was not found in the en locale`, 0, {}, false);
return phraseString;
}
throw new Error(`${phrase} was not found in the default language`);
}
export {
// Ignoring this lint error in case of we want to export more functions from this library
// eslint-disable-next-line import/prefer-default-export
translate,
};