-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.ts
54 lines (41 loc) · 1.15 KB
/
state.ts
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
import type { z } from 'zod'
class State<T extends z.AnyZodObject> {
private state: z.infer<T> | undefined
constructor(initialState?: z.infer<T>) {
this.state = initialState
}
get<K extends keyof z.infer<T>>(key: K): z.infer<T>[K] | undefined {
return this.state?.[key]
}
getAll(): z.infer<T> | undefined {
return this.state
}
async set<K extends keyof z.infer<T>>(key: K, value: z.infer<T>[K]): Promise<z.infer<T>[K]> {
if (!this.state) this.state = {} as z.infer<T>
this.state[key] = value
return value
}
}
export class StateManager {
private MAX_CHANNELS = 100_000
private stateMap: Map<string, State<z.AnyZodObject>>
constructor() {
this.stateMap = new Map()
}
get(channelId: string): State<z.AnyZodObject> {
const existingState = this.stateMap.get(channelId)
if (existingState) return existingState
if (this.stateMap.size >= this.MAX_CHANNELS) {
throw new Error(`Max of ${this.MAX_CHANNELS} channels reached`)
}
const state = new State()
this.stateMap.set(channelId, state)
return state
}
delete(channelId: string): void {
this.stateMap.delete(channelId)
}
getCount(): number {
return this.stateMap.size
}
}