i18n.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. 'en_US': {
  13. 'org.crazydoctor.expressts.start': 'org.crazydoctor.expressts server started on port {port}',
  14. 'org.crazydoctor.expressts.httpError.500': 'Internal server error',
  15. 'org.crazydoctor.expressts.httpError.404': 'Page {url} not found',
  16. 'org.crazydoctor.expressts.swagger.registered': 'Swagger documentation is available on {path}',
  17. 'org.crazydoctor.expressts.swagger.routeGenerated': 'Swagger documentation for route \'{route}\' generated'
  18. }
  19. };
  20. }
  21. public static getInstance(locale?: string): i18nLoader {
  22. if(!i18nLoader.instance)
  23. i18nLoader.instance = new i18nLoader(locale ?? i18nLoader.defaultLocale);
  24. return i18nLoader.instance;
  25. }
  26. public setLocale(locale: string): i18nLoader {
  27. this.locale = locale;
  28. return this;
  29. }
  30. public load(...paths: string[]): i18nLoader {
  31. for(const p of paths) {
  32. try {
  33. const data = fs.readFileSync(p).toString('utf8');
  34. try {
  35. this.loadJson(<i18nMap>JSON.parse(data));
  36. } catch (err) {
  37. console.error('JSON parsing error:', err);
  38. }
  39. } catch(error) {
  40. console.error(`i18n file '${p}' not found.`, error);
  41. }
  42. }
  43. return this;
  44. }
  45. public loadJson(obj: i18nMap): i18nLoader {
  46. for(const locale of Object.keys(obj)) {
  47. if(!this.map[<string>locale]) this.map[locale] = {};
  48. for(const key of Object.keys(obj[locale]))
  49. this.map[locale][key] = obj[locale][key];
  50. }
  51. return this;
  52. }
  53. public get(key: string): string {
  54. let value;
  55. if(!this.map[this.locale] && !this.map[i18nLoader.defaultLocale])
  56. return key;
  57. if(this.map[i18nLoader.defaultLocale])
  58. value = this.map[i18nLoader.defaultLocale][key];
  59. if(this.map[this.locale])
  60. value = this.map[this.locale][key] ?? value;
  61. return value ?? key;
  62. }
  63. }
  64. const $$ = (key: string, params?: KeyParams): string => {
  65. let text = i18nLoader.getInstance().get(key);
  66. if(params) {
  67. for(const param of Object.keys(params)) {
  68. const regex = new RegExp(`\{${param}\}`, 'g');
  69. text = text.replace(regex, params[param]);
  70. }
  71. }
  72. return text;
  73. };
  74. export { i18nLoader, $$ };