* load locales into the client

* extract specific text from locales and fallback to en-US in case of failure
This commit is contained in:
Mylloon 2022-07-21 17:10:25 +02:00
parent 2bde673cb1
commit 8f0096a73c
Signed by: Anri
GPG key ID: A82D63DFF8D1317F

59
src/utils/locales.ts Normal file
View file

@ -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<string, string> = {};
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;
};