-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsocket.ts
More file actions
29 lines (23 loc) · 726 Bytes
/
socket.ts
File metadata and controls
29 lines (23 loc) · 726 Bytes
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
import type { Event, EventLog } from ".";
export type LogId = string & { __brand?: "LogId" };
export function createServerEventLog<E>(
logKey: () => LogId | undefined,
eventLogs: () => Record<LogId, EventLog<E>>,
setEventLogs: (data: Record<LogId, EventLog<E>>) => void
) {
async function appendEvent(event: Event<E>, currentVersion: number) {
const id = logKey();
if (!id) return;
const log = eventLogs()[id];
if (!log) return setEventLogs({ ...eventLogs(), [id]: [event] });
if (log.length !== currentVersion) return;
return setEventLogs({
...eventLogs(),
[id]: [...log, event],
});
}
return {
serverEvents: () => eventLogs()[logKey()!],
appendEvent,
};
}