feat(errors): dynamic fallback locale

This commit is contained in:
Benedikt Rötsch
2018-02-14 16:15:02 +01:00
committed by Benedikt Rötsch
parent 92fcbdf4d8
commit 3c9089af98
3 changed files with 45 additions and 17 deletions

View File

@@ -2,12 +2,19 @@ const fs = require('fs')
const path = require('path')
let translations = null
// Initializes translation dictionary with contents from /public/locales
module.exports.initializeTranslations = () => {
let fallbackLocale = null
/**
* Initializes translation dictionary with contents from /public/locales
*/
function initializeTranslations () {
if (translations) {
return
}
// Default fallbock locale is english
setFallbackLocale('en-US')
translations = {}
const localesPath = path.join(__dirname, 'locales')
@@ -26,6 +33,14 @@ module.exports.initializeTranslations = () => {
}
}
/**
* Sets the fallback locale
* @param locale string Locale code
*/
function setFallbackLocale (locale) {
fallbackLocale = locale
}
/**
* Translate a static string
* @param symbol string Identifier for static text
@@ -33,14 +48,20 @@ module.exports.initializeTranslations = () => {
*
* @returns string
*/
module.exports.translate = (symbol, locale = 'en-US') => {
function translate (symbol, locale = 'en-US') {
const localeDict = translations[locale]
if (!localeDict) {
return `Localization file for ${locale} is not available`
let translatedValue
if (localeDict) {
translatedValue = localeDict[symbol]
}
const translatedValue = localeDict[symbol]
if (!translatedValue) {
return `Translation not found for ${symbol} in ${locale}`
translatedValue = translations[fallbackLocale][symbol]
}
if (!translatedValue) {
return `Translation not found for ${symbol}`
}
return translatedValue
@@ -53,6 +74,11 @@ module.exports.translate = (symbol, locale = 'en-US') => {
*
* @returns boolean
*/
module.exports.translationAvaliable = (symbol, locale = 'en-US') => {
return !!(translations[locale] || {})[symbol]
function translationAvaliable (symbol, locale = 'en-US') {
return !!(translations[locale] || translations[fallbackLocale] || {})[symbol]
}
module.exports.initializeTranslations = initializeTranslations
module.exports.setFallbackLocale = setFallbackLocale
module.exports.translate = translate
module.exports.translationAvaliable = translationAvaliable