SocketWrapper.ts 1.08 KB
import { Socket } from "socket.io";
import { RawMessage, ServerResponse } from "../../common";

export interface SocketWrapper {
  setHandler: (listener: (raw: RawMessage) => ServerResponse<any>) => void;
  setDisconnectHandler: (listener: () => void) => void;
  setPingHandler: (listener: () => void) => void;
  send: (raw: RawMessage) => void;
  sendPing: () => void;
}

export class SocketIoWrapper implements SocketWrapper {
  private socketIo: Socket;

  constructor(socketIo: Socket) {
    this.socketIo = socketIo;
  }

  public setHandler(listener: (raw: RawMessage) => ServerResponse<any>): void {
    this.socketIo.on("msg", (raw: RawMessage, callback: Function) => {
      callback(listener(raw));
    });
  }

  public setDisconnectHandler(listener: () => void) {
    this.socketIo.on("disconnect", () => {
      listener();
    });
  }

  public setPingHandler(listener: () => void) {
    this.socketIo.on("ping", () => {
      listener();
    });
  }

  public send(raw: RawMessage) {
    this.socketIo.emit("msg", raw);
  }

  public sendPing() {
    this.socketIo.emit("ping", {});
  }
}