2020-09-20 15:14:26 +02:00
|
|
|
import { getMessageFromDictionary } from '../stores/dictionary';
|
2021-03-27 17:16:28 +01:00
|
|
|
import { getPossibleLocales } from '../stores/locale';
|
2019-11-20 20:31:55 +01:00
|
|
|
|
2020-11-23 14:50:58 +01:00
|
|
|
export const lookupCache: {
|
|
|
|
[locale: string]: {
|
|
|
|
[messageId: string]: any;
|
|
|
|
};
|
|
|
|
} = {};
|
2019-11-20 20:31:55 +01:00
|
|
|
|
|
|
|
const addToCache = (path: string, locale: string, message: string) => {
|
2020-09-20 15:14:26 +02:00
|
|
|
if (!message) return message;
|
|
|
|
if (!(locale in lookupCache)) lookupCache[locale] = {};
|
|
|
|
if (!(path in lookupCache[locale])) lookupCache[locale][path] = message;
|
|
|
|
|
|
|
|
return message;
|
|
|
|
};
|
2019-11-20 20:31:55 +01:00
|
|
|
|
2021-03-27 17:16:28 +01:00
|
|
|
export const lookup = (path: string, refLocale: string) => {
|
|
|
|
if (refLocale == null) return undefined;
|
2020-09-20 15:14:26 +02:00
|
|
|
|
2021-03-27 17:16:28 +01:00
|
|
|
if (refLocale in lookupCache && path in lookupCache[refLocale]) {
|
|
|
|
return lookupCache[refLocale][path];
|
2019-11-20 20:31:55 +01:00
|
|
|
}
|
|
|
|
|
2021-03-27 17:16:28 +01:00
|
|
|
const locales = getPossibleLocales(refLocale);
|
|
|
|
|
|
|
|
for (let i = 0; i < locales.length; i++) {
|
|
|
|
const locale = locales[i];
|
|
|
|
const message = getMessageFromDictionary(locale, path);
|
2020-09-20 15:14:26 +02:00
|
|
|
|
2021-03-27 17:16:28 +01:00
|
|
|
if (message) {
|
|
|
|
// Used the requested locale as the cache key
|
|
|
|
// Ex: { en: { title: "Title" }}
|
|
|
|
// lookup('title', 'en-GB') should cache with 'en-GB' instead of 'en'
|
|
|
|
return addToCache(path, refLocale, message);
|
|
|
|
}
|
2020-01-08 15:28:44 +01:00
|
|
|
}
|
2019-11-26 01:41:05 +01:00
|
|
|
|
2020-11-23 14:50:58 +01:00
|
|
|
return undefined;
|
2020-09-20 15:14:26 +02:00
|
|
|
};
|