-
Notifications
You must be signed in to change notification settings - Fork 357
Expand file tree
/
Copy pathsettings.ts
More file actions
67 lines (56 loc) · 2.04 KB
/
Copy pathsettings.ts
File metadata and controls
67 lines (56 loc) · 2.04 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
67
import type { LimitedBrowserStorage } from './tests/browser-storage'
export interface SettingStore<Settings> {
set<Key extends keyof Settings>(
key: Key,
value: Settings[Key],
): Promise<void>
get<Key extends keyof Settings>(key: Key): Promise<Settings[Key] | null>
remove<Key extends keyof Settings>(key: Key): Promise<void>
}
export class BrowserSettingsStore<Settings> implements SettingStore<Settings> {
constructor(
private localBrowserStorage: LimitedBrowserStorage,
private options?: {
prefix?: string
},
) {}
async set<Key extends keyof Settings>(
key: Key,
value: Settings[Key],
): Promise<void> {
const storageKey = this._makeStorageKey(key as string)
await this.localBrowserStorage.set({ [storageKey]: value })
}
async get<Key extends keyof Settings>(
key: Key,
): Promise<Settings[Key] | null> {
const storageKey = this._makeStorageKey(key as string)
return this.__rawGet(storageKey)
}
async remove<Key extends keyof Settings>(key: Key): Promise<void> {
const storageKey = this._makeStorageKey(key as string)
await this.localBrowserStorage.remove(storageKey)
}
async __rawGet<ReturnType = any>(key: string): Promise<ReturnType | null> {
const response = await this.localBrowserStorage.get(key)
return (response[key] as ReturnType) ?? null
}
_makeStorageKey(key: string) {
return (this.options?.prefix ?? '') + key
}
}
export class MemorySettingStore<Settings> implements SettingStore<Settings> {
settings: { [Key in keyof Settings]?: Settings[Key] } = {}
async set<Key extends keyof Settings>(
key: Key,
value: Settings[Key],
): Promise<void> {
this.settings[key] = value
}
async get<Key extends keyof Settings>(key: Key): Promise<Settings[Key]> {
return this.settings[key]
}
async remove<Key extends keyof Settings>(key: Key): Promise<void> {
delete this.settings[key]
}
}