UNPKG

@x5e/gink

Version:

an eventually consistent database

102 lines 3.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClientConnection = void 0; const AbstractConnection_1 = require("./AbstractConnection"); const utils_1 = require("./utils"); class ClientConnection extends AbstractConnection_1.AbstractConnection { constructor(options) { super(); const { endpoint, authToken, onData, reconnectOnClose, onOpen, waitFor, logger, onError, } = options; this.onErrorCb = onError; this.onOpen = onOpen; this.endpoint = endpoint; this.onData = onData; this.logger = logger; this.protocols = ["gink"]; if (authToken) this.protocols.push((0, utils_1.encodeToken)(authToken)); this.reconnectOnClose = reconnectOnClose; this.pendingConnect = true; waitFor.then(() => this.connect()); } get readyState() { return (this.websocketClient?.readyState ?? ClientConnection.W3cWebSocket.CLOSED); } get connected() { return this.readyState === ClientConnection.W3cWebSocket.OPEN; } connect() { this.pendingConnect = false; if (this.websocketClient) { if (this.websocketClient.readyState === ClientConnection.W3cWebSocket.OPEN || this.websocketClient.readyState === ClientConnection.W3cWebSocket.CONNECTING) { console.error("connect called but already connected"); return; } } this.websocketClient = new ClientConnection.W3cWebSocket(this.endpoint, this.protocols); if (!this.websocketClient) { throw new Error("Failed to create WebSocket client"); } this.websocketClient.binaryType = "arraybuffer"; this.websocketClient.onopen = this.onOpen.bind(this); this.websocketClient.onmessage = this.onMessage.bind(this); this.websocketClient.onerror = this.onError.bind(this); this.websocketClient.onclose = this.onClose.bind(this); } onError(ev) { this.logger("WebSocket error:", ev); // console.log(`onErrorCb: ${this.onErrorCb}`); if (ev) { this.onErrorCb?.(ev); } else { this.onErrorCb?.(new Error("WebSocket error")); } this.onClosed(); } onClose(ev) { this.logger(`WebSocket closed: code=${ev?.code}, reason=${ev?.reason}, wasClean=${ev?.wasClean}`); this.onClosed(); } onClosed() { this.resetAbstractConnection(); this.websocketClient = undefined; this.notify(); if (this.reconnectOnClose) { if (this.pendingConnect) return; this.logger("will start reconnect in 1 second"); this.pendingConnect = true; setTimeout(() => { this.connect(); }, 1000); } } onMessage(ev) { const data = ev.data; if (data instanceof ArrayBuffer) { const uint8View = new Uint8Array(data); this.onData(uint8View); } else { // We don't expect any non-binary text messages. //console.error(`got non-arraybuffer message: ${data}`); } } send(msg) { this.websocketClient.send(msg); } close() { this.reconnectOnClose = false; this.websocketClient.close(); } } exports.ClientConnection = ClientConnection; ClientConnection.W3cWebSocket = typeof WebSocket === "function" ? WebSocket : eval("require('websocket').w3cwebsocket"); //# sourceMappingURL=ClientConnection.js.map