fetch-graph-locale.js 1.92 KB
Newer Older
1 2 3 4 5
const _ = require('lodash')
const { createApolloFetch } = require('apollo-fetch')

/* global WIKI */

6 7
module.exports = async (localeCode) => {
  WIKI.logger.info(`Fetching locale ${localeCode} from Graph endpoint...`)
8 9

  try {
10 11 12 13
    const apollo = createApolloFetch({
      uri: WIKI.config.graphEndpoint
    })

14 15 16 17 18 19 20 21 22 23
    const respStrings = await apollo({
      query: `query ($code: String!) {
        localization {
          strings(code: $code) {
            key
            value
          }
        }
      }`,
      variables: {
24
        code: localeCode
25 26 27 28 29 30
      }
    })
    const strings = _.get(respStrings, 'data.localization.strings', [])
    let lcObj = {}
    _.forEach(strings, row => {
      if (_.includes(row.key, '::')) { return }
31 32 33
      if (_.isEmpty(row.value)) {
        row.value = row.key
      }
34 35 36
      _.set(lcObj, row.key.replace(':', '.'), row.value)
    })

37
    const locales = await WIKI.cache.get('locales')
38
    if (locales) {
39
      const currentLocale = _.find(locales, ['code', localeCode]) || {}
40
      const existingLocale = await WIKI.models.locales.query().where('code', localeCode).first()
41 42 43 44 45 46 47 48 49 50 51 52 53 54
      if (existingLocale) {
        await WIKI.models.locales.query().patch({
          strings: lcObj
        }).where('code', localeCode)
      } else {
        await WIKI.models.locales.query().insert({
          code: localeCode,
          strings: lcObj,
          isRTL: currentLocale.isRTL,
          name: currentLocale.name,
          nativeName: currentLocale.nativeName,
          availability: currentLocale.availability
        })
      }
55 56 57 58
    } else {
      throw new Error('Failed to fetch cached locales list! Restart server to resolve this issue.')
    }

59
    await WIKI.lang.refreshNamespaces()
60

61
    WIKI.logger.info(`Fetching locale ${localeCode} from Graph endpoint: [ COMPLETED ]`)
62
  } catch (err) {
63
    WIKI.logger.error(`Fetching locale ${localeCode} from Graph endpoint: [ FAILED ]`)
64 65 66
    WIKI.logger.error(err.message)
  }
}