Skip to content

Commit fc1f2cc

Browse files
committed
chore(storage): address PR feedbacks
1 parent abd61df commit fc1f2cc

File tree

2 files changed

+21
-12
lines changed

2 files changed

+21
-12
lines changed

src/__tests__/storage.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ describe('storage', () => {
3131
window.sessionStorage = originalSessionStorage;
3232
});
3333

34-
test('getStorageObject throws if storage contains invalid JSON', () => {
34+
test('returns undefined if storage contains invalid JSON', () => {
3535
window.localStorage.setItem(STORE_KEY, '{invalid json}');
36-
expect(() => get('key1')).toThrow('Failed to retrieve mt-link-javascript-sdk data from storage');
36+
expect(get('key1')).toBeUndefined();
3737
});
3838

3939
test('set, get', () => {

src/storage.ts

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,24 @@ interface StorageData {
44
[key: string]: string;
55
}
66

7+
function isStorageAvailable(storage: Storage): boolean {
8+
try {
9+
const test = '__storage_test__';
10+
storage.setItem(test, test);
11+
storage.removeItem(test);
12+
return true;
13+
} catch (_) {
14+
return false;
15+
}
16+
}
17+
718
function getAvailableStorage(): Storage {
8-
if (typeof window.localStorage !== 'undefined' && window.localStorage !== null) return window.localStorage;
19+
if (isStorageAvailable(window.localStorage)) return window.localStorage;
920

10-
// Fallback to sessionStorage
11-
if (typeof window.sessionStorage !== 'undefined' && window.sessionStorage !== null) return window.sessionStorage;
21+
if (isStorageAvailable(window.sessionStorage)) {
22+
console.error('localStorage not available, falling back to sessionStorage');
23+
return window.sessionStorage;
24+
}
1225

1326
throw new Error('Neither localStorage nor sessionStorage is available');
1427
}
@@ -22,18 +35,14 @@ function getStorageObject(): StorageData {
2235

2336
return JSON.parse(stringifiedData);
2437
} catch (error) {
25-
throw new Error(`Failed to retrieve ${STORE_KEY} data from storage`);
38+
console.error(`Failed to load or parse data from storage key "${STORE_KEY}":`, error);
39+
return {};
2640
}
2741
}
2842

2943
function saveStorageObject(data: StorageData): void {
3044
const storage = getAvailableStorage();
31-
32-
try {
33-
storage.setItem(STORE_KEY, JSON.stringify(data));
34-
} catch (error) {
35-
throw new Error('Failed to save data to storage');
36-
}
45+
storage.setItem(STORE_KEY, JSON.stringify(data));
3746
}
3847

3948
export function get(key: string): string | undefined {

0 commit comments

Comments
 (0)