localization.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const _ = require('lodash')
  2. const dotize = require('dotize')
  3. const i18nMW = require('i18next-express-middleware')
  4. const i18next = require('i18next')
  5. const Promise = require('bluebird')
  6. /* global WIKI */
  7. module.exports = {
  8. engine: null,
  9. namespaces: [],
  10. init() {
  11. this.namespaces = WIKI.data.localeNamespaces
  12. this.engine = i18next
  13. this.engine.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. })
  22. return this
  23. },
  24. attachMiddleware (app) {
  25. app.use(i18nMW.handle(this.engine))
  26. },
  27. async 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. async loadLocale(locale) {
  41. return Promise.fromCallback(cb => {
  42. return this.engine.loadLanguages(locale, cb)
  43. })
  44. },
  45. async setCurrentLocale(locale) {
  46. return Promise.fromCallback(cb => {
  47. return this.engine.changeLanguage(locale, cb)
  48. })
  49. }
  50. }