Files
tidefront/apps/web/src/lib/live.ts
T
db9979 2a79899fb8 Andere Spieler und Saison: Rangliste, Spielerübersicht, Nachrichten, Saisonende mit Wertung und Reset
- Tabellen message, season, season_result (Abschnitt am Ende von schema.ts, ohne Migration)
- Rangliste aus Kampfberichten und aktuellem Stand (scoring.ts), 30 s zwischengespeichert
- Nachrichten mit Ratenlimit, Systemnachrichten, WebSocket-Meldung messages
- Saisonende season_end (season.ts): Endstand, Auszeichnungen, Reset in einer Transaktion, Journal ausgeglichen
- Oberfläche: Meldungen mit Reitern Berichte, Nachrichten, Rangliste; Ruhmeshalle; Saisonhinweise
- SEASON_DAYS in Compose und .env.example, Handbuch, REGELN und BAUAUFTRAG ergänzt
2026-11-26 20:08:25 +01:00

58 lines
2.1 KiB
TypeScript

// WebSocket /ws: Änderungsmeldungen invalidieren passende Abfragen; Neuverbindung mit Rückstau.
import { useEffect } from "react";
import { queryClient, trpc } from "./trpc.ts";
import { noteServerTime } from "./time.ts";
const FILTERS: Record<string, () => { queryKey: readonly unknown[] }[]> = {
base: () => [trpc.base.pathFilter()],
missions: () => [trpc.base.pathFilter()],
reports: () => [trpc.report.pathFilter(), trpc.base.pathFilter(), trpc.social.ranking.pathFilter()],
market: () => [trpc.market.pathFilter(), trpc.base.pathFilter()],
map: () => [trpc.world.pathFilter()],
messages: () => [trpc.social.messages.pathFilter()],
// Saisonwechsel: die ganze Welt ist neu.
season: () => [
trpc.season.pathFilter(), trpc.social.pathFilter(), trpc.base.pathFilter(), trpc.world.pathFilter(),
trpc.report.pathFilter(), trpc.market.pathFilter(),
],
};
export function useLive(enabled: boolean): void {
useEffect(() => {
if (!enabled) return;
let ws: WebSocket | null = null;
let stopped = false;
let delay = 1000;
let timer: ReturnType<typeof setTimeout> | undefined;
const connect = () => {
const proto = location.protocol === "https:" ? "wss:" : "ws:";
ws = new WebSocket(`${proto}//${location.host}/ws`);
ws.onopen = () => {
delay = 1000;
// Nach Neuverbindung alles frisch holen (Meldungen könnten verpasst sein).
void queryClient.invalidateQueries();
};
ws.onmessage = (ev) => {
try {
const msg = JSON.parse(String(ev.data)) as { kind: string; serverNow?: number };
if (typeof msg.serverNow === "number") noteServerTime(msg.serverNow);
for (const f of FILTERS[msg.kind]?.() ?? []) void queryClient.invalidateQueries(f);
} catch {
/* ignorieren */
}
};
ws.onclose = () => {
if (stopped) return;
timer = setTimeout(connect, delay);
delay = Math.min(30000, delay * 2);
};
};
connect();
return () => {
stopped = true;
clearTimeout(timer);
ws?.close();
};
}, [enabled]);
}