2026-10-16 00:08:38 +03:00
|
|
|
import { AuthUser } from "../../src/auth";
|
|
|
|
|
import { OnClientConnectionChange, OnMessage, RTMT } from "../../src/rtmt/rtmt";
|
|
|
|
|
|
|
|
|
|
export type SentMessage = { clientID: string, channel: string, message: any };
|
|
|
|
|
|
|
|
|
|
// In-memory RTMT: tests connect users, send messages as them and inspect what the server sent back.
|
|
|
|
|
export class FakeRtmt implements RTMT {
|
|
|
|
|
readonly sent: SentMessage[] = [];
|
|
|
|
|
private readonly listeners = new Map<string, OnMessage>();
|
|
|
|
|
private readonly online = new Map<string, AuthUser>();
|
2026-10-16 00:21:09 +03:00
|
|
|
private readonly connectionListeners: OnClientConnectionChange[] = [];
|
2026-10-16 00:08:38 +03:00
|
|
|
|
|
|
|
|
connect(user: AuthUser) {
|
|
|
|
|
this.online.set(user.id, user);
|
2026-10-16 00:21:09 +03:00
|
|
|
this.connectionListeners.forEach((listener) => listener(user.id, true));
|
2026-10-16 00:08:38 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
disconnect(userId: string) {
|
|
|
|
|
this.online.delete(userId);
|
2026-10-16 00:21:09 +03:00
|
|
|
this.connectionListeners.forEach((listener) => listener(userId, false));
|
2026-10-16 00:08:38 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
receive(userId: string, channel: string, message: Object = {}) {
|
|
|
|
|
const listener = this.listeners.get(channel);
|
|
|
|
|
if (!listener) throw new Error(`No listener for ${channel}`);
|
|
|
|
|
listener(userId, message);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
messagesTo(userId: string, channel: string): any[] {
|
|
|
|
|
return this.sent.filter((m) => m.clientID === userId && m.channel === channel).map((m) => m.message);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
sendMessage(clientID: string, channel: string, message: Object) {
|
|
|
|
|
// Copy, like serialising over the wire would.
|
|
|
|
|
this.sent.push({ clientID, channel, message: JSON.parse(JSON.stringify(message)) });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
listenMessage(channel: string, callback: OnMessage) {
|
|
|
|
|
this.listeners.set(channel, callback);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isClientOnline(clientID: string): boolean {
|
|
|
|
|
return this.online.has(clientID);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
getUser(clientID: string): AuthUser | undefined {
|
|
|
|
|
return this.online.get(clientID);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
listenOnClientConnectionChange(onUserConnectionChange: OnClientConnectionChange): void {
|
2026-10-16 00:21:09 +03:00
|
|
|
this.connectionListeners.push(onUserConnectionChange);
|
2026-10-16 00:08:38 +03:00
|
|
|
}
|
|
|
|
|
}
|