Skip to content

Commit

Permalink
Add an optional "absolute" flage to translationKeyExists
Browse files Browse the repository at this point in the history
This flag allows us to ask not just that a translation key exists, but
also whether it is an "absolute" key, ie. one that can be used by
`i18n.translate`.

Currently the method just checks whether a subtree exists with the given
key, but that tree is not necessarily a leaf node that would result in a
translated string, just a translated set of objects. This flag allows us
the ability to safely check that a translation exists before calling
translate() to avoid triggering onError.
  • Loading branch information
ryanwilsonperkin committed Feb 5, 2024
1 parent a9f4dad commit 3d072b0
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/strange-windows-drive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/react-i18n': minor
---

Add absolute option to I18n#translationKeyExists
5 changes: 3 additions & 2 deletions packages/react-i18n/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,10 @@ export class I18n {
}
}

translationKeyExists(id: string) {
translationKeyExists(id: string, absolute = false) {
try {
getTranslationTree(id, this.translations, this.locale);
const result = getTranslationTree(id, this.translations, this.locale);
if (absolute) return typeof result === 'string';
return true;
} catch (error) {
return false;
Expand Down
32 changes: 32 additions & 0 deletions packages/react-i18n/src/tests/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2372,6 +2372,38 @@ describe('I18n', () => {
const result = i18n.translationKeyExists(key);
expect(result).toBe(false);
});

describe('when absolute is true', () => {
it('returns true if the key exists and is a string', () => {
const mockResult = 'translated string';
getTranslationTree.mockReturnValue(mockResult);

const i18n = new I18n(defaultTranslations, defaultDetails);
const result = i18n.translationKeyExists('hello', true);

expect(result).toBe(true);
});

it('returns false if the key exists and is an object', () => {
const mockResult = {hello: 'translated string'};
getTranslationTree.mockReturnValue(mockResult);

const i18n = new I18n(defaultTranslations, defaultDetails);
const result = i18n.translationKeyExists('hello', true);

expect(result).toBe(false);
});

it('returns false if the key does not exist', () => {
const mockResult = undefined;
getTranslationTree.mockReturnValue(mockResult);

const i18n = new I18n(defaultTranslations, defaultDetails);
const result = i18n.translationKeyExists('goodbye', true);

expect(result).toBe(false);
});
});
});

// we only test a few use cases as this method is simply a wrapper for the similarly
Expand Down

0 comments on commit 3d072b0

Please sign in to comment.