Improve i18n caching (#12030)

* fix indentation

* wip: cache i18n responses

* cache i18n browser script to disk

* typos

* misc fixes
This commit is contained in:
Matteo Pagliazzi
2020-05-05 20:31:33 +02:00
committed by GitHub
parent 446122d7b8
commit e5f1f3b279
6 changed files with 69 additions and 29 deletions

View File

@@ -1,26 +1,13 @@
import _ from 'lodash';
import nconf from 'nconf';
import {
translations,
momentLangs,
availableLanguages,
BROWSER_SCRIPT_CACHE_PATH,
geti18nBrowserScript,
} from '../../libs/i18n';
const IS_PROD = nconf.get('IS_PROD');
const api = {};
function geti18nBrowserScript (language) {
const langCode = language.code;
return `(function () {
if (!window) return;
window['habitica-i18n'] = ${JSON.stringify({
availableLanguages,
language,
strings: translations[langCode],
momentLang: momentLangs[langCode],
})};
})()`;
}
/**
* @api {get} /api/v3/i18n/browser-script Returns the i18n JS script.
* @apiDescription Returns the i18n JS script to make
@@ -33,14 +20,16 @@ api.geti18nBrowserScript = {
method: 'GET',
url: '/i18n/browser-script',
async handler (req, res) {
const language = _.find(availableLanguages, { code: req.language });
if (IS_PROD) {
res.sendFile(`${BROWSER_SCRIPT_CACHE_PATH}${req.language}.js`);
} else {
res.set({
'Content-Type': 'application/javascript',
});
res.set({
'Content-Type': 'application/javascript',
});
const jsonResString = geti18nBrowserScript(language);
res.status(200).send(jsonResString);
const jsonResString = geti18nBrowserScript(req.language);
res.status(200).send(jsonResString);
}
},
};