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

/* global WIKI */

6
module.exports = async () => {
7 8 9
  WIKI.logger.info('Syncing locales with Graph endpoint...')

  try {
10 11 12
    const apollo = createApolloFetch({
      uri: WIKI.config.graphEndpoint
    })
NGPixel's avatar
NGPixel committed
13 14 15 16

    // -> Fetch locales list

    const respList = await apollo({
17 18 19
      query: `{
        localization {
          locales {
20
            availability
21 22 23 24 25 26 27 28 29 30
            code
            name
            nativeName
            isRTL
            createdAt
            updatedAt
          }
        }
      }`
    })
NGPixel's avatar
NGPixel committed
31
    const locales = _.sortBy(_.get(respList, 'data.localization.locales', []), 'name').map(lc => ({...lc, isInstalled: (lc.code === 'en')}))
32
    WIKI.cache.set('locales', locales)
NGPixel's avatar
NGPixel committed
33 34 35

    // -> Download locale strings

NGPixel's avatar
NGPixel committed
36
    if (WIKI.config.lang.autoUpdate) {
37 38 39 40 41 42 43 44 45 46 47
      const activeLocales = WIKI.config.lang.namespacing ? WIKI.config.lang.namespaces : [WIKI.config.lang.code]
      for (const currentLocale of activeLocales) {
        const localeInfo = _.find(locales, ['code', currentLocale])

        const respStrings = await apollo({
          query: `query ($code: String!) {
            localization {
              strings(code: $code) {
                key
                value
              }
NGPixel's avatar
NGPixel committed
48
            }
49 50 51
          }`,
          variables: {
            code: currentLocale
NGPixel's avatar
NGPixel committed
52
          }
53 54 55 56 57
        })
        const strings = _.get(respStrings, 'data.localization.strings', [])
        let lcObj = {}
        _.forEach(strings, row => {
          if (_.includes(row.key, '::')) { return }
58 59 60
          if (_.isEmpty(row.value)) {
            row.value = row.key
          }
61 62 63 64 65 66 67 68
          _.set(lcObj, row.key.replace(':', '.'), row.value)
        })

        await WIKI.models.locales.query().update({
          code: currentLocale,
          strings: lcObj,
          isRTL: localeInfo.isRTL,
          name: localeInfo.name,
69 70
          nativeName: localeInfo.nativeName,
          availability: localeInfo.availability
71
        }).where('code', currentLocale)
NGPixel's avatar
NGPixel committed
72

73 74
        WIKI.logger.info(`Pulled latest locale updates for ${localeInfo.name} from Graph endpoint: [ COMPLETED ]`)
      }
NGPixel's avatar
NGPixel committed
75
    }
76

77
    await WIKI.lang.refreshNamespaces()
78

79 80 81 82 83 84
    WIKI.logger.info('Syncing locales with Graph endpoint: [ COMPLETED ]')
  } catch (err) {
    WIKI.logger.error('Syncing locales with Graph endpoint: [ FAILED ]')
    WIKI.logger.error(err.message)
  }
}