File size: 609 Bytes
9e9075b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { WebSocketServer } from "ws";
import jwt from "jsonwebtoken";

const clients = new Set();

export function initAdminWS(server) {
  const wss = new WebSocketServer({ server, path: "/ws/admin" });

  wss.on("connection", (ws, req) => {
    const token = new URL(req.url, "http://x").searchParams.get("token");
    try {
      jwt.verify(token, process.env.JWT_SECRET);
      clients.add(ws);
    } catch {
      ws.close();
    }
    ws.on("close", () => clients.delete(ws));
  });
}

export function emitAdminAlert(data) {
  const msg = JSON.stringify(data);
  clients.forEach((ws) => ws.send(msg));
}