0

I am new to i18n and have an existing repository that uses it. I noticed different syntax for using i18n throughout the repository and am wondering what is the best way.

I am confused about the structure below and which syntax option is best (I think it's better to be consistent with the syntax and use only 1 option). Could someone perhaps explain?

In controllers I find:

var responses = require('../../locales/en.json');

let message = responses.authorisation.flashes['welcome'];
return res.status(200).json({
  success: true,
  message,
  token,
  user: userData
});

In middleware the syntax is as follows:

req.flash('error', req.__('organisation.not-found'));

And in app.js I find:

const flash = require('connect-flash');
const flashMiddleware = require('./middleware/flashMiddleware');

const i18n = require('i18n');
i18n.configure({
  locales: [
    'en', 'nl'
  ],
  register: global,
  directory: path.join(__dirname, 'locales'),
  defaultLocale: 'en',
  objectNotation: true,
  updateFiles: false
});

flashMiddleware.js contains (I'm not sure what this does):

const flashMiddleware = (req, res, next) => {
  res.locals.flashes = req.flash();

  next();
};

module.exports = flashMiddleware;
Marty
  • 2,132
  • 4
  • 21
  • 47

1 Answers1

0

Both your first and last code blocks don't appear to be using i18n at all. Instead, the first code block is loading the JSON for en and using it directly. It's not clear what the flash stuff is using, I don't see anything in that code doing localization.

The middleware syntax, using __ on req, appears to be the standard way you use this library in middleware.

There are other ways to use it as well that are detailed in the documentation.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks, I've added the i18n code that is in app.js in the OP. I think that does the localization (it might also not be completely set up for internationalisation, since at the moment the site is in only 1 language). Is there a difference, for example in performance or otherwise, between the two syntaxes? I mean wouldn't it make sense to also use the `__` syntax in the controller? (for consistency) – Marty Dec 30 '19 at 11:30
  • @Marty - I think it does, and not just for consistency. Presumably at some point the app will be in more than one language (otherwise, why use localization files and `i18n` at all?). The controller code assumes English, so if/when you go to multiple languages, you have to edit the controller code to match the middleware code anyway. Might as well set out as you mean to go on... :-) (I realize the code is already there, so "set out" isn't really accurate, but...) – T.J. Crowder Dec 30 '19 at 11:46