diff options
Diffstat (limited to 'source/library/state/storage.ts')
| -rw-r--r-- | source/library/state/storage.ts | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/source/library/state/storage.ts b/source/library/state/storage.ts new file mode 100644 index 0000000..a24096a --- /dev/null +++ b/source/library/state/storage.ts @@ -0,0 +1,77 @@ + + + +/*** EXPORT ------------------------------------------- ***/ + +export type Storage = { + get<T>(key: string): T | null; + remove(key: string): void; + set<T>(key: string, value: T): void; +}; + +export function createLocalStorage(namespace: string): Storage { + const prefix = `${namespace}:`; + + function available(): boolean { + try { + return typeof globalThis.localStorage !== "undefined"; + } catch { + return false; + } + } + + return { + get<T>(key: string): T | null { + if (!available()) + return null; + + const raw = globalThis.localStorage.getItem(prefix + key); + + if (raw === null) + return null; + + try { + return JSON.parse(raw) as T; + } catch { + return null; + } + }, + remove(key: string): void { + if (!available()) + return; + + globalThis.localStorage.removeItem(prefix + key); + }, + set<T>(key: string, value: T): void { + if (!available()) + return; + + globalThis.localStorage.setItem(prefix + key, JSON.stringify(value)); + } + }; +} + +export function createMemoryStorage(): Storage { + const store = new Map<string, string>(); + + return { + get<T>(key: string): T | null { + const raw = store.get(key); + + if (raw === undefined) + return null; + + try { + return JSON.parse(raw) as T; + } catch { + return null; + } + }, + remove(key: string): void { + store.delete(key); + }, + set<T>(key: string, value: T): void { + store.set(key, JSON.stringify(value)); + } + }; +} |