locale.js 947 B

12345678910111213141516171819202122232425262728293031
  1. const fs = require('fs');
  2. const path = require('path');
  3. const { FluentBundle, FluentResource } = require('@fluent/bundle');
  4. const localesPath = path.resolve(__dirname, '../public/locales');
  5. const locales = fs.readdirSync(localesPath);
  6. function makeBundle(locale) {
  7. const bundle = new FluentBundle(locale, { useIsolating: false });
  8. bundle.addResource(
  9. new FluentResource(
  10. fs.readFileSync(path.resolve(localesPath, locale, 'send.ftl'), 'utf8')
  11. )
  12. );
  13. return [locale, bundle];
  14. }
  15. const bundles = new Map(locales.map(makeBundle));
  16. module.exports = function getTranslator(locale) {
  17. const defaultBundle = bundles.get('en-US');
  18. const bundle = bundles.get(locale) || defaultBundle;
  19. return function(id, data) {
  20. if (bundle.hasMessage(id)) {
  21. return bundle.formatPattern(bundle.getMessage(id).value, data);
  22. }
  23. return defaultBundle.formatPattern(
  24. defaultBundle.getMessage(id).value,
  25. data
  26. );
  27. };
  28. };