feat: locales #27
1 changed files with 59 additions and 0 deletions
59
src/utils/locales.ts
Normal file
59
src/utils/locales.ts
Normal 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;
|
||||
};
|
Loading…
Reference in a new issue