feat(packages/sui-i18n): Upgrade to node-polyglot v2.5.0
Description
With this Pull Request, we have migrated from [email protected] to the last one [email protected]. The main reason to upgrade it is to be able to log the translation issues from outside by providing an onMissingKey function callback. As you will see in the example section, you could send metrics or trace logs and prevent translation issues in your web app.
Before continuing, I suggest you read issue #1731 to learn more about the current problem and how to reproduce it in all of our marketplaces. A quick resume is to avoid those console:
I proposed 3 approaches/scenarios to achieve it:
- 1️⃣ When onMissingKey callback is configured, prevent writing the
console.warn, as is onnode-polyglotat this line - 2️⃣ Send the onMissingKey and write the
console.warnat the same time. - 3️⃣ Send the onMissingKey (in case of been configured) and add a flag
logMissingKeyto prevent writing theconsole.warn.
Scenario 3️⃣ is the one that people wanted.
So, when you create a 18n instance:
-
allowMissing: a boolean to control whether missing keys in atcall are allowed. Iffalse, by default, a missing key is returned and a warning is issued. -
onMissingKey: ifallowMissingistrue, and this option is a function, then it will be called instead of the default functionality. Arguments passed to it arekey,options, andlocale. The return of this function will be used as a translation fallback whenpolyglot.t('missing.key')is called (hint: return the key). -
logMissingKey: by default is true to not break the current workflow. In case you want to avoid logs, you should passlogMissingKey: trueand will skip it inallowMissingandonMissingKeyprevious scenarios.
Related Issue
fix #1731
Example
How to track translation errors from outside.
// First, create a onMissingKeyCallback function to do your stuff
function onMissingKeyCallback(key, opts, currentLocale, tokenRegex, pluralRules) {
// Here you can send some metrics to DataDog
logger.metric(...)
// Also you can log an error and trace it in OpenSearch to know which key is causing the error
try {
throw new Error(`Missing translation for key: ${key} on language ${currentLocale}`)
} catch (err) {
logger.error({
name: 'your_log_name',
message: err.message,
stack: err.stack
})
}
return key
}
// Second, modify or create your adapter and pass your onMissingKey function
const adapter = new PolyglotAdapter({onMissingKey: onMissingKeyCallback})
// And third, pass this adapter to your i18n instance
const i18n = new I18n({adapter})
How to avoid writing console.warn into browser console
// First, modify or create your adapter and pass the logMissingKey with false value
const adapter = new PolyglotAdapter({logMissingKey: false})
// At the end, pass this adapter to your i18n instance
const i18n = new I18n({adapter})
TODO
- [ ] Test it in a production web app
- [ ] Update Readme before merge
Next week I'll try to publish a beta and test it on one of our websites 🚀!