FIX: Don't crash when MF definitions are missing

Currently, if MF definitions are missing (typically because there’s a
compilation error), `I18n.messageFormat` will try to access
`I18n._mfMessages.hasMessage` resulting in a crash that will in turn
crash Ember.

This patch addresses the issue by using the optional chaining operator
making the `I18n.messageFormat` method return a "Missing Key" message.
MF strings won’t be rendered properly, but the site will stay usable.
This commit is contained in:
Loïc Guitaut 2024-07-29 16:52:14 +02:00 committed by Loïc Guitaut
parent e81fc27a0f
commit cfa4f07378
2 changed files with 18 additions and 1 deletions

View File

@ -379,7 +379,7 @@ export class I18n {
}
messageFormat(key, options) {
const message = this._mfMessages.hasMessage(
const message = this._mfMessages?.hasMessage(
key,
this._mfMessages.locale,
this._mfMessages.defaultLocale

View File

@ -12,6 +12,7 @@ module("Unit | Utility | i18n", function (hooks) {
this._translations = I18n.translations;
this._extras = I18n.extras;
this._pluralizationRules = { ...I18n.pluralizationRules };
this._mfMessages = I18n._mfMessages;
I18n.locale = "fr";
@ -109,6 +110,7 @@ module("Unit | Utility | i18n", function (hooks) {
I18n.translations = this._translations;
I18n.extras = this._extras;
I18n.pluralizationRules = this._pluralizationRules;
I18n._mfMessages = this._mfMessages;
});
test("defaults", function (assert) {
@ -356,4 +358,19 @@ module("Unit | Utility | i18n", function (hooks) {
);
});
});
test("messageFormat", function (assert) {
assert.ok(
I18n.messageFormat("posts_likes_MF", { count: 2, ratio: "high" }).match(
/2 replies/
),
"It works properly"
);
I18n._mfMessages = null;
assert.strictEqual(
I18n.messageFormat("posts_likes_MF", { count: 2, ratio: "high" }),
"Missing Key: posts_likes_MF",
"Degrades gracefully if MF definitions are not available."
);
});
});