-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
81ded9c
commit 972f2a9
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
/** | ||
* A localStorage utility class that can be | ||
* used to remember keyed preferences/options | ||
*/ | ||
|
||
const KEY_PREFIX = "__documentcloud_"; | ||
|
||
export interface StorageManager { | ||
key: (subkey: string) => string; | ||
} | ||
|
||
export class StorageManager { | ||
constructor(key: string) { | ||
this.key = (subkey) => `${KEY_PREFIX}${key}_${subkey}`; | ||
} | ||
|
||
get<R, T>(key: string, defaultValue?: T): R | T | null { | ||
try { | ||
const value = JSON.parse(localStorage.getItem(this.key(key))); | ||
if (value === null) return defaultValue ?? null; | ||
return value; | ||
} catch (e) { | ||
// Local storage not available | ||
return defaultValue ?? null; | ||
} | ||
} | ||
|
||
set<V>(key: string, value: V) { | ||
try { | ||
localStorage.setItem(this.key(key), JSON.stringify(value)); | ||
} catch (e) { | ||
// Local storage not available | ||
} | ||
} | ||
|
||
remove(key: string) { | ||
try { | ||
localStorage.removeItem(this.key(key)) | ||
} catch (e) { | ||
// Local storage not available | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { test, expect } from 'vitest'; | ||
import { StorageManager } from "../storage"; | ||
|
||
test("StorageManager", () => { | ||
const s = new StorageManager('settings'); | ||
expect(s.key('property')).toEqual('__documentcloud_settings_property'); | ||
s.set('property', 12345); | ||
expect(s.get('property')).toEqual(12345); | ||
expect(s.get('unsetProp', 67890)).toEqual(67890); | ||
expect(s.get('unsetProp')).toBeNull(); | ||
s.remove('property'); | ||
expect(s.get('property')).toBeNull(); | ||
}); |