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.

52 lines
1.3 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: ['common', 'admin', 'auth', 'errors', 'git'],
  11. init() {
  12. this.engine = i18next
  13. this.engine.use(i18nBackend).init({
  14. load: 'languageOnly',
  15. ns: this.namespaces,
  16. defaultNS: 'common',
  17. saveMissing: false,
  18. preload: [wiki.config.site.lang],
  19. lng: wiki.config.site.lang,
  20. fallbackLng: 'en',
  21. backend: {
  22. loadPath: path.join(wiki.SERVERPATH, 'locales/{{lng}}/{{ns}}.json')
  23. }
  24. })
  25. return this
  26. },
  27. getByNamespace(locale, namespace) {
  28. if (this.engine.hasResourceBundle(locale, namespace)) {
  29. let data = this.engine.getResourceBundle(locale, namespace)
  30. return _.map(dotize.convert(data), (value, key) => {
  31. return {
  32. key,
  33. value
  34. }
  35. })
  36. } else {
  37. throw new Error('Invalid locale or namespace')
  38. }
  39. },
  40. loadLocale(locale) {
  41. return Promise.fromCallback(cb => {
  42. return this.engine.loadLanguages(locale, cb)
  43. })
  44. },
  45. setCurrentLocale(locale) {
  46. return Promise.fromCallback(cb => {
  47. return this.engine.changeLanguage(locale, cb)
  48. })
  49. }
  50. }