From 8ec15b78038cc67f68a28d8de9524dc87184ab2b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 21 Jul 2022 15:13:39 +0200 Subject: [PATCH] * language relative to user, not global anymore * add comments * store all the localizations instead of unique one * move localization function to utils/ folder --- README.md | 1 - src/utils/client.ts | 50 ++++++++------------------------------------- 2 files changed, 9 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 2d66706..8eed6c6 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,6 @@ services: | Nom | Commentaire | Valeur par défaut | :-----------: | :-----------: | :-: | TOKEN_DISCORD | Token Discord | Aucune -| LANGUAGE | Langue du bot | en --- ### Références diff --git a/src/utils/client.ts b/src/utils/client.ts index 41c10cd..e458b09 100644 --- a/src/utils/client.ts +++ b/src/utils/client.ts @@ -1,17 +1,20 @@ import { Client, Collection, Intents } from 'discord.js'; -import { readFileSync, existsSync } from 'fs'; +import { readFileSync } from 'fs'; import { SlashCommandBuilder } from '@discordjs/builders'; +import { loadLocales } from './locales'; const { version } = JSON.parse(readFileSync('./package.json').toString()); declare module 'discord.js' { // eslint-disable-next-line no-shadow export interface Client { + /** Store the configuration */ config: { version: string, token_discord: string | undefined, - lang: string + default_lang: string }, + /** Store all the slash commands */ commands: Collection< string, { @@ -19,7 +22,8 @@ declare module 'discord.js' { interaction: (interaction: CommandInteraction, client: Client) => unknown } >, - locale: Map + /** Store all the localizations */ + locales: Map> } } @@ -31,51 +35,15 @@ export default async () => { ], }); - // Store the client configuration client.config = { version: version, token_discord: process.env.TOKEN_DISCORD, - lang: process.env.LANGUAGE ?? '', + default_lang: 'en-US', }; - // Store the commands available client.commands = new Collection(); - // Store all the strings - client.locale = await getLocale(client); + client.locales = await loadLocales(client.config.default_lang); return client; }; - - -/** - * Get all the strings corresponding to the locales specified in env variable - * @returns Collection of strings - */ -const getLocale = async (client: Client) => { - const default_lang = 'en-US'; - - // Check if there is a defined valid value - const old_path = __dirname.split('/'); - old_path.pop(); - const lang = client.config.lang === undefined ? default_lang : existsSync( - `${old_path.join('/')}/locales/${client.config.lang}.json`, - ) ? client.config.lang : default_lang; - - // Fallback to default language in case lang isn't valid - if (client.config.lang !== lang) { - client.config.lang = lang; - } - - const file: { - [key: string]: string - } = await import( - `../locales/${lang}.json` - ); - - return new Map( - Object.keys(file).map(key => { - return [key, file[key]]; - }), - ); -};