-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
42 lines (34 loc) · 1.05 KB
/
server.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
import type * as Party from 'partykit/server';
export default class Server implements Party.Server {
constructor(readonly room: Party.Room) {
setInterval(() => {
// update DB
}, 30_000);
}
async onConnect(
connection: Party.Connection<unknown>,
ctx: Party.ConnectionContext,
): Promise<void> {
const currentCount = (await this.room.storage.get('counter')) ?? 0;
connection.send(`${currentCount}`);
}
async onMessage(
message: string | ArrayBuffer | ArrayBufferView,
sender: Party.Connection<unknown>,
): Promise<void> {
if (message === 'increment') {
let currentCount =
((await this.room.storage.get('counter')) as number) ?? 0;
this.room.storage.put('counter', ++currentCount);
this.room.broadcast(`${currentCount}`);
}
}
onClose(connection: Party.Connection<unknown>): void | Promise<void> {
const connections = [...this.room.getConnections()].length;
if (connections === 0) {
// flush to DB
// clear interval
}
}
}
Server satisfies Party.Worker;