Skip to content

Commit

Permalink
Cache latin1 fix (#45)
Browse files Browse the repository at this point in the history
* cache latin1 fix

* version

* cache test
  • Loading branch information
laliconfigcat authored Dec 20, 2023
1 parent f5b6ffb commit e017412
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 5 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "configcat-react",
"version": "4.0.0",
"version": "4.1.0",
"scripts": {
"build": "npm run build:esm && npm run build:cjs",
"build:esm": "tsc -p tsconfig.build.esm.json && gulp esm",
Expand Down
10 changes: 10 additions & 0 deletions src/Cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { LocalStorageCache } from "./Cache";

it("LocalStorageCache works with non latin 1 characters", () => {
const cache = new LocalStorageCache();
const key = "testkey";
const text = "äöüÄÖÜçéèñışğ⢙✓😀";
cache.set(key, text);
const retrievedValue = cache.get(key);
expect(retrievedValue).toStrictEqual(text);
});
16 changes: 14 additions & 2 deletions src/Cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { IConfigCatCache } from "configcat-common";
export class LocalStorageCache implements IConfigCatCache {
set(key: string, value: string): void {
try {
localStorage.setItem(key, btoa(value));
localStorage.setItem(key, this.b64EncodeUnicode(value));
}
catch (ex) {
// local storage is unavailable
Expand All @@ -14,12 +14,24 @@ export class LocalStorageCache implements IConfigCatCache {
try {
const configString = localStorage.getItem(key);
if (configString) {
return atob(configString);
return this.b64DecodeUnicode(configString);
}
}
catch (ex) {
// local storage is unavailable or invalid cache value in localstorage
}
return void 0;
}

private b64EncodeUnicode(str: string): string {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (_, p1) {
return String.fromCharCode(parseInt(p1, 16))
}));
}

private b64DecodeUnicode(str: string): string {
return decodeURIComponent(Array.prototype.map.call(atob(str), function (c: string) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
}).join(''));
}
}

0 comments on commit e017412

Please sign in to comment.