Skip to content

Commit

Permalink
Update to ping client every 10s (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rabrennie committed May 23, 2023
1 parent 08bf153 commit 4ca26c4
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
12 changes: 10 additions & 2 deletions src/lib/room/SseClient.server.ts
Expand Up @@ -5,19 +5,27 @@ import crypto from 'crypto';
export class SseClient {
eventEmitter: EventEmitter;
id: string;
interval: NodeJS.Timer;

constructor() {
this.eventEmitter = new EventEmitter();
this.id = crypto.randomBytes(16).toString('base64url');
this.interval = setInterval(() => {
this.send('ping', Date.now());
}, 10000);
}

send<T extends RoomEvent>(event: T, data: RoomEvents[T]) {
console.log('send', event, data);
console.log(this.id, 'send', event, data);
this.eventEmitter.emit('send', event, data);
}

delaySend<T extends RoomEvent>(event: T, delay: number, data: RoomEvents[T]) {
console.log('delaySend', event, data);
this.eventEmitter.emit('delaySend', event, delay, data);
this.eventEmitter.emit(this.id, 'delaySend', event, delay, data);
}

close() {
clearInterval(this.interval);
}
}
6 changes: 4 additions & 2 deletions src/lib/room/events.ts
Expand Up @@ -32,13 +32,15 @@ export type RoomEvent =
| 'room:users:update'
| 'room:choices:update'
| 'room:state:update'
| 'room:album:eliminated';
| 'room:album:eliminated'
| 'ping';

export const RoomEventSchemas = {
'room:users:update': usersUpdateSchema,
'room:choices:update': choicesUpdateSchema,
'room:state:update': stateUpdateSchema,
'room:album:eliminated': albumEliminatedSchema
'room:album:eliminated': albumEliminatedSchema,
ping: z.number()
} satisfies {
[key in RoomEvent]: z.ZodSchema;
};
Expand Down
3 changes: 3 additions & 0 deletions src/routes/room/[room]/events/+server.ts
Expand Up @@ -29,8 +29,11 @@ export const GET = (async ({ params }) => {
this.cancel?.();
}
});

sseClient.send('ping', Date.now());
},
cancel() {
sseClient.close();
const clients = rooms.get(params.room) ?? {};
if (clients[sseClient.id]) {
delete clients[sseClient.id];
Expand Down

0 comments on commit 4ca26c4

Please sign in to comment.