31 lines
1.1 KiB
TypeScript
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));
|
|
}
|