J
J
JIakki2015-08-17 23:24:51
JavaScript
JIakki, 2015-08-17 23:24:51

How to make the function more extensible in the future?

How to make the function simpler and more extensible in the future?

var langs, lang, words;

module.exports = function (req, res, next) {
  if(req.session.lang) {
    lang = req.session.lang
  } else {
    langs = req.headers["accept-language"];
    lang = langs[0] + langs[1];
  }

  res.locals = require('./langs/' + lang + '.json')

  next();
}

зарание спасибо

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Shemsedinov, 2015-08-18
@JIakki

1. How did you parse req.headers so quickly, there could be something like this, for example:

Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Language: da, en-gb;q=0.8, en;q=0.7
Accept-Language: cmn-Hans-CN
Accept-Language: i-enochian
Accept-Language: cel-gaulish
Accept-Language: *

or even more complex, see the specification:
https://tools.ietf.org/html/bcp47
www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
There are libraries to parse correctly:
https:/ /github.com/gagle/node-bcp47
https://github.com/tinganho/node-accept-language
2. Doing require inside a handler is terrible. This is a synchronous file read operation that needs to be done when the server starts. You need to put all the languages ​​in one file and read it at startup, and then access the directory in memory.
3. Middleware detected, and of course, do not use next, if it is, of course, a more or less serious loaded project in production, and not a prototype or a layout.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question