localization.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import i18next from 'i18next'
  2. import i18nextXHR from 'i18next-xhr-backend'
  3. import i18nextCache from 'i18next-localstorage-cache'
  4. import VueI18Next from '@panter/vue-i18next'
  5. import _ from 'lodash'
  6. import gql from 'graphql-tag'
  7. /* global siteConfig, graphQL */
  8. module.exports = {
  9. VueI18Next,
  10. init() {
  11. i18next
  12. .use(i18nextXHR)
  13. .use(i18nextCache)
  14. .init({
  15. backend: {
  16. loadPath: '{{lng}}/{{ns}}',
  17. parse: (data) => data,
  18. ajax: (url, opts, cb, data) => {
  19. let langParams = url.split('/')
  20. graphQL.query({
  21. query: gql`
  22. query($locale: String!, $namespace: String!) {
  23. translations(locale:$locale, namespace:$namespace) {
  24. key
  25. value
  26. }
  27. }
  28. `,
  29. variables: {
  30. locale: langParams[0],
  31. namespace: langParams[1]
  32. }
  33. }).then(resp => {
  34. let ns = {}
  35. if (resp.data.translations.length > 0) {
  36. resp.data.translations.forEach(entry => {
  37. _.set(ns, entry.key, entry.value)
  38. })
  39. }
  40. return cb(ns, {status: '200'})
  41. }).catch(err => {
  42. console.error(err)
  43. return cb(null, {status: '404'})
  44. })
  45. }
  46. },
  47. cache: {
  48. enabled: true,
  49. expiration: 60 * 60 * 1000
  50. },
  51. defaultNS: 'common',
  52. lng: siteConfig.lang,
  53. fallbackLng: siteConfig.lang,
  54. ns: ['common', 'auth']
  55. })
  56. return new VueI18Next(i18next)
  57. }
  58. }