sync-graph-locales.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const _ = require('lodash')
  2. const { createApolloFetch } = require('apollo-fetch')
  3. /* global WIKI */
  4. module.exports = async () => {
  5. WIKI.logger.info('Syncing locales with Graph endpoint...')
  6. try {
  7. const apollo = createApolloFetch({
  8. uri: WIKI.config.graphEndpoint
  9. })
  10. // -> Fetch locales list
  11. const respList = await apollo({
  12. query: `{
  13. localization {
  14. locales {
  15. code
  16. name
  17. nativeName
  18. isRTL
  19. createdAt
  20. updatedAt
  21. }
  22. }
  23. }`
  24. })
  25. const locales = _.sortBy(_.get(respList, 'data.localization.locales', []), 'name').map(lc => ({...lc, isInstalled: (lc.code === 'en')}))
  26. WIKI.cache.set('locales', locales)
  27. // -> Download locale strings
  28. if (WIKI.config.lang.autoUpdate) {
  29. const activeLocales = WIKI.config.lang.namespacing ? WIKI.config.lang.namespaces : [WIKI.config.lang.code]
  30. for (const currentLocale of activeLocales) {
  31. const localeInfo = _.find(locales, ['code', currentLocale])
  32. const respStrings = await apollo({
  33. query: `query ($code: String!) {
  34. localization {
  35. strings(code: $code) {
  36. key
  37. value
  38. }
  39. }
  40. }`,
  41. variables: {
  42. code: currentLocale
  43. }
  44. })
  45. const strings = _.get(respStrings, 'data.localization.strings', [])
  46. let lcObj = {}
  47. _.forEach(strings, row => {
  48. if (_.includes(row.key, '::')) { return }
  49. if (_.isEmpty(row.value)) { row.value = row.key }
  50. _.set(lcObj, row.key.replace(':', '.'), row.value)
  51. })
  52. await WIKI.models.locales.query().update({
  53. code: currentLocale,
  54. strings: lcObj,
  55. isRTL: localeInfo.isRTL,
  56. name: localeInfo.name,
  57. nativeName: localeInfo.nativeName
  58. }).where('code', currentLocale)
  59. WIKI.logger.info(`Pulled latest locale updates for ${localeInfo.name} from Graph endpoint: [ COMPLETED ]`)
  60. }
  61. }
  62. await WIKI.lang.refreshNamespaces()
  63. WIKI.logger.info('Syncing locales with Graph endpoint: [ COMPLETED ]')
  64. } catch (err) {
  65. WIKI.logger.error('Syncing locales with Graph endpoint: [ FAILED ]')
  66. WIKI.logger.error(err.message)
  67. }
  68. }