You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.4 KiB

  1. const _ = require('lodash')
  2. const dotize = require('dotize')
  3. const i18nBackend = require('i18next-node-fs-backend')
  4. const i18next = require('i18next')
  5. const path = require('path')
  6. const Promise = require('bluebird')
  7. /* global wiki */
  8. module.exports = {
  9. engine: null,
  10. namespaces: [],
  11. init() {
  12. this.namespaces = wiki.data.localeNamespaces
  13. this.engine = i18next
  14. this.engine.use(i18nBackend).init({
  15. load: 'languageOnly',
  16. ns: this.namespaces,
  17. defaultNS: 'common',
  18. saveMissing: false,
  19. preload: [wiki.config.site.lang],
  20. lng: wiki.config.site.lang,
  21. fallbackLng: 'en',
  22. backend: {
  23. loadPath: path.join(wiki.SERVERPATH, 'locales/{{lng}}/{{ns}}.yml')
  24. }
  25. })
  26. return this
  27. },
  28. async getByNamespace(locale, namespace) {
  29. if (this.engine.hasResourceBundle(locale, namespace)) {
  30. let data = this.engine.getResourceBundle(locale, namespace)
  31. return _.map(dotize.convert(data), (value, key) => {
  32. return {
  33. key,
  34. value
  35. }
  36. })
  37. } else {
  38. throw new Error('Invalid locale or namespace')
  39. }
  40. },
  41. async loadLocale(locale) {
  42. return Promise.fromCallback(cb => {
  43. return this.engine.loadLanguages(locale, cb)
  44. })
  45. },
  46. async setCurrentLocale(locale) {
  47. return Promise.fromCallback(cb => {
  48. return this.engine.changeLanguage(locale, cb)
  49. })
  50. }
  51. }