feat: locales #27

Merged
Anri merged 26 commits from lang into main 2022-07-22 11:46:48 +02:00
Showing only changes of commit 8f0096a73c - Show all commits

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;
};