datopian / frontend-v2

CKAN / Data Portal frontend as microservice in pure Javascript (Node).
http://tech.datopian.com/frontend/
MIT License
38 stars 18 forks source link

[fix][s] Configure Moment locale based on i18n #160

Closed gavram closed 4 years ago

gavram commented 4 years ago

@anuveyatsu Please, would you review this PR.

This fixes configuring of Moment locale.

Description Moment locale was not changing according to defaultLocale cookie value. Idea was to set Moment locale in frontend-v2 itself, not from Theme, so this can be reused in all cases that needs translations. In this particular case we use moment.fromNow() function which returns human readable value from datetime value. Our starting point was:

i18n.configure({
  cookie: 'defaultLocale',
  directory: __dirname + translationsDir,
  locales: config.get('LOCALES') || ['en'],
  defaultLocale: config.get('DEFAULT_LOCALE') || 'en'
})

// also set it up for moment:
moment.locale(i18n.getLocale())

Implementation

  1. In this solution I didn't use locales: config.get('LOCALES') || ['en'],, because i18n by default reads /i18n folder's translations files, so it overrides previous setting in i18n.configure.

  2. Function getLocale() always returns en locale, no matter what defaultLocale value is. So I decided to use express middleware to obtain locale value for Moment:

app.use(function (req, res, next) {
    moment.locale(i18n.getLocale(req))

    next()
  });

Conclusion This solution is tested in Montreal theme and works as we expected. One more important thing is that this do not change implementation of i18n, so there is no need to change documentation.