summaryrefslogtreecommitdiffhomepage
path: root/src/adapters/local-storage/index.ts
blob: 72135ce02c55ce9e53573c7afce50ee1545c52d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
export interface LocalStore<T> {
	load(): T | null;
	save(value: T): void;
	clear(): void;
}

export interface CreateLocalStoreOptions {
	storage?: Storage | undefined;
}

function createNoopStore<T>(): LocalStore<T> {
	return {
		load() {
			return null;
		},
		save() {},
		clear() {},
	};
}

export function createLocalStore<T>(key: string, opts?: CreateLocalStoreOptions): LocalStore<T> {
	let storage: Storage | undefined;
	if (opts !== undefined && "storage" in opts) {
		storage = opts.storage;
	} else {
		storage = globalThis.localStorage;
	}

	if (storage === undefined || storage === null) {
		return createNoopStore<T>();
	}

	return {
		load(): T | null {
			try {
				const raw = storage.getItem(key);
				if (raw === null) {
					return null;
				}
				return JSON.parse(raw) as T;
			} catch {
				return null;
			}
		},

		save(value: T): void {
			try {
				storage.setItem(key, JSON.stringify(value));
			} catch {
				// Swallow quota / write errors — persistence is best-effort.
			}
		},

		clear(): void {
			storage.removeItem(key);
		},
	};
}