diff --git a/src/utils/locales.ts b/src/utils/locales.ts new file mode 100644 index 0000000..58e89e4 --- /dev/null +++ b/src/utils/locales.ts @@ -0,0 +1,59 @@ +import { Client } from 'discord.js'; +import { readdir } from 'fs/promises'; + +/** + * Load the localizations files + */ +export const loadLocales = async () => { + // Check if there is a defined valid value + const old_path = __dirname.split('/'); + old_path.pop(); + + const files = await readdir(`${old_path.join('/')}/locales`); + + const locales = new Map(); + await Promise.all( + files.map(async lang => { + const content: { + [key: string]: string + } = await import( + `../locales/${lang}` + ); + + locales.set( + lang.split('.')[0], + new Map( + Object.keys(content).map(str => { + return [str, content[str]]; + }), + ) + ); + }) + ); + + return locales; +}; + + +/** + * Builds a dictionary, if a translation is not available, + * we fallback to en-US. + * @param client Client + * @param text Name of string to fetch + * @returns the dictionary + */ +export const getLocale = (client: Client, text: string) => { + const data: Record = {}; + + client.locales.forEach((locale, lang) => { + const str = locale.get(text) + ?? client.locales.get(client.config.default_lang)?.get(text); + + if (str === undefined) { + throw 'Missing locales'; + } + data[lang] = str; + }); + + return data; +};