Skip to content

Commit

Permalink
Adds a storage manager
Browse files Browse the repository at this point in the history
  • Loading branch information
allanlasser committed Jul 24, 2024
1 parent 81ded9c commit 972f2a9
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/lib/utils/storage.ts
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
}
}
}
13 changes: 13 additions & 0 deletions src/lib/utils/tests/storage.test.ts
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();
});

0 comments on commit 972f2a9

Please sign in to comment.