Files
patchpass/Backend/src/lib/WsHub.ts
T
Space-Banane 7e05dd918c
Deploy / Build (push) Successful in 28s
Deploy / Test & Lint (push) Failing after 29s
Deploy / Build and Push Docker Image (push) Has been skipped
Patchpass V1
2026-07-18 20:14:44 +02:00

31 lines
1.1 KiB
TypeScript

import { Channel } from "rjweb-server";
/**
* Real-time hub. One RJWEB Channel per human account; the websocket endpoint
* subscribes each authenticated socket to its owner's channel via
* `ctr.printChannel(getUserChannel(userId))`. Any server-side event for that
* user (new notification, request state change) is published to the channel and
* fanned out to every open socket.
*/
const userChannels = new Map<number, Channel<string>>();
export function getUserChannel(userId: number): Channel<string> {
let channel = userChannels.get(userId);
if (!channel) {
channel = new Channel<string>();
userChannels.set(userId, channel);
}
return channel;
}
export type RealtimeEvent =
| { kind: "notification"; notification: unknown; unreadCount: number }
| { kind: "request_event"; event: string; requestPublicId: string }
| { kind: "ping"; at: string };
export async function publishToUser(userId: number, event: RealtimeEvent): Promise<void> {
const channel = userChannels.get(userId);
if (!channel) return; // nobody connected — nothing to push
await channel.send("text", JSON.stringify(event));
}