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.

57 lines
1.5 KiB

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