E
E
Evgeny Tereshchenko2018-03-23 10:20:01
JavaScript
Evgeny Tereshchenko, 2018-03-23 10:20:01

How to switch language on the fly in Loopback 3.0?

The task is to translate the error texts.
On the client, I change the header Accept Language on the backend, there is such a middleware

var SG = require('strong-globalize');
var Negotiator = require('negotiator');

module.exports = function(options) {
  var allowedLangs = ['en', 'de', 'ru'];
  return function localeHandler(req, res, next) {
    var lang = new Negotiator(req).language(allowedLangs);
    var g = SG();
    g.setLanguage(lang);
    next();
  };
};

And the language changes, but this does not affect other SG instances in any way, and even if g.setLanguage is called immediately before calling the desired message, nothing changes.
g.setLanguage('de');
this.message = g.f(
  'The %s instance is not valid. Details: %s.',
   context ? '`' + context + '`' : 'model',
   formatErrors(obj.errors, obj.toJSON()) || '(unknown)'
);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question