lareact-i18n
Version:
Allows to connect your `Laravel` Framework localization files with `React`.
45 lines (36 loc) • 1.59 kB
text/typescript
import recognizer from '../utils/recognizer';
import LocaleFileInterface from '../interfaces/locale-file';
/**
* Resolves the language files for a given locale.
*
* @param files - The available translation files.
* @param locale - The target locale.
*/
export default function resolver(
files: Record<string, any> | Record<string, () => Promise<any>>,
locale: string
): LocaleFileInterface[] {
const { isJsonLocale, isPhpLocale, getJsonFiles, getPhpFiles } = recognizer(files);
const jsonFiles = isJsonLocale(locale) ? getJsonFiles(locale).map((file) => files[file]) : [];
const phpFiles = isPhpLocale(locale) ? getPhpFiles(locale).map((file) => files[file]) : [];
const getType = (obj: any) => Object.prototype.toString.call(obj);
const mergeObjects = (fileList: any[]) => {
return fileList.reduce((acc, file) => {
if (getType(file) === '[object Object]') {
return { ...acc, ...file };
}
if (getType(file) === '[object Function]') {
return { ...acc, ...file() };
}
return acc;
}, {});
};
const mergedJson = mergeObjects(jsonFiles);
const mergedPhp = mergeObjects(phpFiles);
const asyncJson = jsonFiles.find((file) => ['[object Promise]', '[object Module]'].includes(getType(file)));
const asyncPhp = phpFiles.find((file) => ['[object Promise]', '[object Module]'].includes(getType(file)));
if (asyncJson || asyncPhp) {
return [asyncJson ? asyncJson : { default: mergedJson }, asyncPhp ? asyncPhp : { default: mergedPhp }];
}
return [{ default: mergedJson }, { default: mergedPhp }];
}