Newer
Older
navi-1 / client / js / ws.js
@Eugene Sukhodolskiy Eugene Sukhodolskiy on 8 Apr 978 bytes Persistent sessions and client module refactor
/** WebSocket client wrapper. */

export class WsClient {
  #ws = null;
  #sessionId = null;
  #handlers = {};

  connect(sessionId, handlers) {
    this.disconnect();
    this.#sessionId = sessionId;
    this.#handlers = handlers;

    const proto = location.protocol === 'https:' ? 'wss' : 'ws';
    this.#ws = new WebSocket(`${proto}://${location.host}/ws/sessions/${sessionId}`);

    this.#ws.onopen    = () => handlers.onOpen?.();
    this.#ws.onclose   = (e) => handlers.onClose?.(e);
    this.#ws.onerror   = (e) => handlers.onError?.(e);
    this.#ws.onmessage = (e) => handlers.onMessage?.(JSON.parse(e.data));
  }

  send(content) {
    if (this.#ws?.readyState === WebSocket.OPEN) {
      this.#ws.send(JSON.stringify({ type: 'message', content }));
      return true;
    }
    return false;
  }

  disconnect() {
    this.#ws?.close();
    this.#ws = null;
    this.#sessionId = null;
  }

  get ready() {
    return this.#ws?.readyState === WebSocket.OPEN;
  }
}