2019-11-20 20:31:55 +01:00
|
|
|
// todo invalidate only keys with null values
|
|
|
|
import resolvePath from 'object-resolve-path'
|
|
|
|
|
|
|
|
import { hasLocaleDictionary } from '../stores/dictionary'
|
2019-11-24 03:38:15 +01:00
|
|
|
import { getFallbackOf } from '../stores/locale'
|
2019-11-20 20:31:55 +01:00
|
|
|
|
|
|
|
const lookupCache: Record<string, Record<string, string>> = {}
|
|
|
|
|
|
|
|
const addToCache = (path: string, locale: string, message: string) => {
|
2019-11-21 02:20:56 +01:00
|
|
|
if (!message) return message
|
2019-11-20 20:31:55 +01:00
|
|
|
if (!(locale in lookupCache)) lookupCache[locale] = {}
|
|
|
|
if (!(path in lookupCache[locale])) lookupCache[locale][path] = message
|
|
|
|
return message
|
|
|
|
}
|
|
|
|
|
|
|
|
export const lookupMessage = (
|
|
|
|
dictionary: any,
|
|
|
|
path: string,
|
|
|
|
locale: string
|
|
|
|
): string => {
|
|
|
|
if (locale == null) return null
|
|
|
|
if (locale in lookupCache && path in lookupCache[locale]) {
|
|
|
|
return lookupCache[locale][path]
|
|
|
|
}
|
|
|
|
if (hasLocaleDictionary(locale)) {
|
|
|
|
if (path in dictionary[locale]) {
|
|
|
|
return addToCache(path, locale, dictionary[locale][path])
|
|
|
|
}
|
|
|
|
const message = resolvePath(dictionary[locale], path)
|
|
|
|
if (message) return addToCache(path, locale, message)
|
|
|
|
}
|
|
|
|
|
|
|
|
return addToCache(
|
|
|
|
path,
|
|
|
|
locale,
|
2019-11-24 03:38:15 +01:00
|
|
|
lookupMessage(dictionary, path, getFallbackOf(locale))
|
2019-11-20 20:31:55 +01:00
|
|
|
)
|
|
|
|
}
|