File size: 2,118 Bytes
3162254
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import type { Socket } from "socket.io-client";
import io from "socket.io-client";
import type {
  CallBackState,
  ClientEventKeys,
  ClientHandler,
  ServerEventKeys,
  ServerFn,
  ServerHandler,
  SocketEventParams,
} from "../../types/websocket";
import { CLINT_EVENT } from "../../types/websocket";
import { IS_MOBILE } from "laser-utils";
import { DEVICE_TYPE } from "../../types/client";
import { getUniqueId } from "laser-utils";

export class SocketClient {
  public readonly id: string;
  public readonly socket: Socket<ServerHandler, ClientHandler>;
  constructor(wss: string) {
    const STORAGE_KEY = "WEBSOCKET-ID";
    // https://socket.io/docs/v4/server-socket-instance/#socketid
    this.id = sessionStorage?.getItem(STORAGE_KEY) || getUniqueId(8);
    sessionStorage?.setItem(STORAGE_KEY, this.id);
    console.log("Client WebSocket ID:", this.id);
    const socket = io(wss, { transports: ["websocket"] });
    this.socket = socket;
    this.socket.on("connect", this.onConnect);
    this.socket.on("disconnect", this.onDisconnect);
  }

  public on = <T extends ServerEventKeys>(key: T, cb: ServerFn<T>) => {
    // @ts-expect-error unknown
    this.socket.on(key, cb);
  };

  public off = <T extends ServerEventKeys>(key: T, cb: ServerFn<T>) => {
    // @ts-expect-error unknown
    this.socket.off(key, cb);
  };

  public emit = <T extends ClientEventKeys>(
    key: T,
    payload: SocketEventParams[T],
    callback?: (state: CallBackState) => void
  ) => {
    // @ts-expect-error unknown
    this.socket.emit(key, payload, callback);
  };

  private onConnect = () => {
    // https://socket.io/docs/v4/server-socket-instance/#socketid
    this.emit(CLINT_EVENT.JOIN_ROOM, {
      id: this.id,
      device: IS_MOBILE ? DEVICE_TYPE.MOBILE : DEVICE_TYPE.PC,
    });
  };

  private onDisconnect = () => {
    this.emit(CLINT_EVENT.LEAVE_ROOM, { id: this.id });
  };

  public destroy = () => {
    this.socket.emit(CLINT_EVENT.LEAVE_ROOM, { id: this.id });
    this.socket.off("connect", this.onConnect);
    this.socket.off("disconnect", this.onDisconnect);
    this.socket.close();
  };
}