locale/LocaleManager.js

  1. "use strict";
  2. // LocaleManager.ts - Locales (noud02)
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. const fs = require("fs");
  5. const i18next = require("i18next");
  6. const i18backend = require("i18next-node-fs-backend");
  7. const path = require("path");
  8. /**
  9. * Locale manager class
  10. *
  11. * @export
  12. * @class LocaleManager
  13. */
  14. class LocaleManager {
  15. /**
  16. * Initializes the locale manager
  17. *
  18. * @returns {Promise<i18next.TranslationFunction>}
  19. */
  20. init() {
  21. return new Promise((resolve, reject) => {
  22. const opts = {
  23. addPath: `${__dirname}/../../i18n/{{lng}}/{{ns}}.missing.json`,
  24. jsonIndent: 4,
  25. loadPath: `${__dirname}/../../i18n/{{lng}}/{{ns}}.json`,
  26. };
  27. const langs = [];
  28. for (const dir of fs.readdirSync(path.join(__dirname, "..", "..", "i18n/"))) {
  29. if (fs.statSync(path.join(__dirname, "..", "..", "i18n", dir)).isDirectory()) {
  30. langs.push(dir);
  31. }
  32. }
  33. i18next.use(i18backend).init({
  34. backend: opts,
  35. fallbackLng: "en",
  36. lng: "en",
  37. load: "all",
  38. preload: langs,
  39. }, (err, t) => {
  40. if (err) {
  41. return reject(err);
  42. }
  43. this.t = t;
  44. return resolve(t);
  45. });
  46. });
  47. }
  48. /**
  49. * Reloads the locales
  50. *
  51. * @returns {Promise<void>}
  52. */
  53. reload() {
  54. return new Promise((resolve, reject) => {
  55. i18next.reloadResources();
  56. i18next.on("loaded", resolve);
  57. i18next.on("failedLoading", reject);
  58. });
  59. }
  60. /**
  61. * Returns a localized permission
  62. *
  63. * @param {string} perm Permission
  64. * @returns {string}
  65. */
  66. localizedPerm(perm) {
  67. return this.t(`localized_perms.${perm}`);
  68. }
  69. /**
  70. * Returns a localized string
  71. *
  72. * @param {string | string[]} str string
  73. * @param {map} opt options
  74. * @returns {string}
  75. */
  76. str(str, opt) {
  77. return this.t(str, opt);
  78. }
  79. }
  80. exports.LocaleManager = LocaleManager;