localization.js 1.83 KB
Newer Older
1
import i18next from 'i18next'
Nick's avatar
Nick committed
2 3
import Backend from 'i18next-chained-backend'
import LocalStorageBackend from 'i18next-localstorage-backend'
4 5
import i18nextXHR from 'i18next-xhr-backend'
import VueI18Next from '@panter/vue-i18next'
6
import _ from 'lodash'
7

8
/* global siteConfig, graphQL */
9

10
import localeQuery from 'gql/common/common-localization-query-translations.gql'
11

12
export default {
13 14 15
  VueI18Next,
  init() {
    i18next
Nick's avatar
Nick committed
16
      .use(Backend)
17 18
      .init({
        backend: {
Nick's avatar
Nick committed
19 20 21 22 23 24
          backends: [
            LocalStorageBackend,
            i18nextXHR
          ],
          backendOptions: [
            {
25
              expirationTime: 1000 * 60 * 60 * 24 // 24h
Nick's avatar
Nick committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
            },
            {
              loadPath: '{{lng}}/{{ns}}',
              parse: (data) => data,
              ajax: (url, opts, cb, data) => {
                let langParams = url.split('/')
                graphQL.query({
                  query: localeQuery,
                  variables: {
                    locale: langParams[0],
                    namespace: langParams[1]
                  }
                }).then(resp => {
                  let ns = {}
                  if (_.get(resp, 'data.localization.translations', []).length > 0) {
                    resp.data.localization.translations.forEach(entry => {
                      _.set(ns, entry.key, entry.value)
                    })
                  }
                  return cb(ns, {status: '200'})
                }).catch(err => {
                  console.error(err)
                  return cb(null, {status: '404'})
49 50
                })
              }
Nick's avatar
Nick committed
51 52
            }
          ]
53 54 55
        },
        defaultNS: 'common',
        lng: siteConfig.lang,
Nick's avatar
Nick committed
56 57
        load: 'currentOnly',
        lowerCaseLng: true,
58
        fallbackLng: siteConfig.lang,
59
        ns: ['common', 'auth']
60 61 62 63
      })
    return new VueI18Next(i18next)
  }
}