-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathtauri-store-state.ts
More file actions
66 lines (51 loc) · 1.5 KB
/
tauri-store-state.ts
File metadata and controls
66 lines (51 loc) · 1.5 KB
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
59
60
61
62
63
64
65
66
import { isTauri } from "@tauri-apps/api/core";
import { load, type Store } from "@tauri-apps/plugin-store";
import type { StateStorage } from "zustand/middleware";
import { debounce } from "@/hooks/use-debounce";
const hasBrowserWindow = () => typeof window !== "undefined";
export class TauriStoreState implements StateStorage {
private store: Store | null = null;
private debouncedSave: (() => void) | null = null;
private initialized = false;
constructor(public storeName: string) {}
async init() {
if (this.initialized) {
return;
}
this.initialized = true;
if (!hasBrowserWindow()) {
// When server-rendering we skip initializing the Tauri store.
return;
}
if (!isTauri()) {
// Running in a regular browser; fall back to default persist storage.
return;
}
this.store = await load(this.storeName);
if (!this.store) {
throw new Error(`Failed to load store: ${this.storeName}`);
}
this.debouncedSave = debounce(() => this.store?.save(), 1 * 1000) ?? null;
}
async getItem(name: string) {
if (!this.store) {
return null;
}
const res = await this.store.get<string>(name);
return res ?? null;
}
async setItem(name: string, value: string) {
if (!this.store) {
return;
}
await this.store.set(name, value);
this.debouncedSave?.();
}
async removeItem(name: string) {
if (!this.store) {
return;
}
await this.store.delete(name);
this.debouncedSave?.();
}
}