i18n.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import fs from 'fs';
  2. import { i18nMap } from './i18nMap';
  3. import { KeyParams } from './KeyParams';
  4. class i18nLoader {
  5. private static instance: i18nLoader;
  6. private readonly map: i18nMap;
  7. private locale: string;
  8. public static defaultLocale = 'en_US';
  9. public constructor(locale: string) {
  10. this.locale = locale;
  11. this.map = <i18nMap>{};
  12. }
  13. public static getInstance(locale?: string): i18nLoader {
  14. if(!i18nLoader.instance)
  15. i18nLoader.instance = new i18nLoader(locale ?? i18nLoader.defaultLocale);
  16. return i18nLoader.instance;
  17. }
  18. public setLocale(locale: string): i18nLoader {
  19. this.locale = locale;
  20. return this;
  21. }
  22. public load(...paths: string[]): i18nLoader {
  23. for(const p of paths) {
  24. try {
  25. const data = fs.readFileSync(p).toString('utf8');
  26. try {
  27. this.loadJson(<i18nMap>JSON.parse(data));
  28. } catch (err) {
  29. console.error('JSON parsing error:', err);
  30. }
  31. } catch(error) {
  32. console.error(`i18n file '${p}' not found.`, error);
  33. }
  34. }
  35. return this;
  36. }
  37. public loadJson(obj: i18nMap): i18nLoader {
  38. for(const locale of Object.keys(obj)) {
  39. if(!this.map[<string>locale]) this.map[locale] = {};
  40. for(const key of Object.keys(obj[locale]))
  41. this.map[locale][key] = obj[locale][key];
  42. }
  43. return this;
  44. }
  45. public get(key: string): string {
  46. let value;
  47. if(!this.map[this.locale] && !this.map[i18nLoader.defaultLocale])
  48. return key;
  49. if(this.map[i18nLoader.defaultLocale])
  50. value = this.map[i18nLoader.defaultLocale][key];
  51. if(this.map[this.locale])
  52. value = this.map[this.locale][key] ?? value;
  53. return value ?? key;
  54. }
  55. }
  56. const $$ = (key: string, params?: KeyParams): string => {
  57. let text = i18nLoader.getInstance().get(key);
  58. if(params) {
  59. for(const param of Object.keys(params)) {
  60. const regex = new RegExp(`\{${param}\}`, 'g');
  61. text = text.replace(regex, params[param]);
  62. }
  63. }
  64. return text;
  65. };
  66. export { i18nLoader, $$ };