locale/LocaleManager.js

"use strict";
// LocaleManager.ts - Locales (noud02)
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const i18next = require("i18next");
const i18backend = require("i18next-node-fs-backend");
const path = require("path");
/**
 * Locale manager class
 *
 * @export
 * @class LocaleManager
 */
class LocaleManager {
    /**
     * Initializes the locale manager
     *
     * @returns {Promise<i18next.TranslationFunction>}
     */
    init() {
        return new Promise((resolve, reject) => {
            const opts = {
                addPath: `${__dirname}/../../i18n/{{lng}}/{{ns}}.missing.json`,
                jsonIndent: 4,
                loadPath: `${__dirname}/../../i18n/{{lng}}/{{ns}}.json`,
            };
            const langs = [];
            for (const dir of fs.readdirSync(path.join(__dirname, "..", "..", "i18n/"))) {
                if (fs.statSync(path.join(__dirname, "..", "..", "i18n", dir)).isDirectory()) {
                    langs.push(dir);
                }
            }
            i18next.use(i18backend).init({
                backend: opts,
                fallbackLng: "en",
                lng: "en",
                load: "all",
                preload: langs,
            }, (err, t) => {
                if (err) {
                    return reject(err);
                }
                this.t = t;
                return resolve(t);
            });
        });
    }
    /**
     * Reloads the locales
     *
     * @returns {Promise<void>}
     */
    reload() {
        return new Promise((resolve, reject) => {
            i18next.reloadResources();
            i18next.on("loaded", resolve);
            i18next.on("failedLoading", reject);
        });
    }
    /**
     * Returns a localized permission
     *
     * @param {string} perm Permission
     * @returns {string}
     */
    localizedPerm(perm) {
        return this.t(`localized_perms.${perm}`);
    }
    /**
     * Returns a localized string
     *
     * @param {string | string[]} str string
     * @param {map} opt options
     * @returns {string}
     */
    str(str, opt) {
        return this.t(str, opt);
    }
}
exports.LocaleManager = LocaleManager;