From 8f0096a73cb764c40cf609ac88d7305ab40a6391 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 21 Jul 2022 17:10:25 +0200 Subject: [PATCH] * load locales into the client * extract specific text from locales and fallback to en-US in case of failure --- src/utils/locales.ts | 59 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/utils/locales.ts 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; +};