Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cache): implement caching for intl data #233

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions packages/react-intl-universal/src/ReactIntlUniversal.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,14 @@ class ReactIntlUniversal {
}

try {
const msgFormatter = new IntlMessageFormat(msg, currentLocale, formats);
return msgFormatter.format(variables);
const cacheKey = key + JSON.stringify(variables) + currentLocale;
let computedValue = this.cache[cacheKey];
if (typeof computedValue === 'undefined') {
const msgFormatter = new IntlMessageFormat(msg, currentLocale, formats);
computedValue = msgFormatter.format(variables);
this.cache[cacheKey] = computedValue;
}
return computedValue;
} catch (err) {
this.options.warningHandler(
`react-intl-universal format message failed for key='${key}'.`,
Expand Down Expand Up @@ -188,6 +194,8 @@ class ReactIntlUniversal {
constants.defaultFormats
);

this.cache = Object.create(null)

return new Promise((resolve, reject) => {
// init() will not load external common locale data anymore.
// But, it still return a Promise for abckward compatibility.
Expand Down
12 changes: 12 additions & 0 deletions packages/react-intl-universal/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -368,3 +368,15 @@ test("Resolve directly if the environment is not browser", async () => {
});
expect(result).toBe(undefined);
});

test("cache", () => {
const key = "HELLO";
const variables = { name: 'World' };
const currentLocale = "en-US"
const cacheKey = key + JSON.stringify(variables) + currentLocale;

intl.init({ locales, currentLocale });

expect(intl.get(key, variables)).toBe("Hello, World");
expect(intl.cache[cacheKey]).toBe("Hello, World");
});