UNPKG

@genexus/web-standard-functions

Version:

GeneXus JavaScript standard functions library for web generators

121 lines 3.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WS = exports.Options = void 0; const log = require("loglevel"); class Options { constructor() { this.autoReconnect = true; this.autoReconnectInterval = 5 * 1000; this.maxReconnectAttempts = 10; } } exports.Options = Options; class WS { constructor() { this.logger = log.getLogger("websocket"); this.options = new Options(); this.currentReconnectAttempts = 0; } /** * Connects to a WebSocket Server endpoint using the URL specified. * @param {string} url WebSocket server URL. * @param {Options} options Connection options (optional). */ async open(url, options) { return new Promise((resolve, reject) => { if (!this.supported()) { this.logger.error("WebSocket is not supported in this browser"); reject(); return; } if (!url.startsWith("ws")) { this.logger.error("Not supported websocket protocol (ws:// or wss:// supported only):", url); reject(); return; } this.options = options || this.options; this.url = url; this.openImpl(resolve, reject); }); } /** * Closes the websocket connection. * @param {number} code Error code for closed connection (optional) * @param {string} reason Reason description for closed connection (optional) */ close(code, reason) { if (this.websocket) { this.websocket.close(code, reason); } } /** * Send the data to WebSocket Server currently connected. * @param {any} data Message data. */ send(data) { // TODO: Check if websocket state is open. Otherwise try to reconnect. let ok = true; try { this.websocket.send(data); } catch (e) { this.logger.error("Send Error", e); ok = false; } return true; } openImpl(resolve, reject) { this.websocket = new WebSocket(this.url); this.websocket.onopen = (e) => { this.currentReconnectAttempts = 0; log.debug("Connection established", this.url); resolve(); if (this.onOpen) { this.onOpen(e); } }; this.websocket.onmessage = (e) => { this.logger.debug("Message received", e.data); if (this.onMessage) { this.onMessage(e); } }; this.websocket.onclose = e => { switch (e.code) { case 1000: this.logger.debug("Connection closed"); if (this.onClose) { this.onClose(e); } reject(); break; default: this.reconnect(resolve, reject); break; } }; this.websocket.onerror = e => { this.logger.error("Connection error", JSON.stringify(e)); if (this.onError) { this.onError(e); } this.reconnect(resolve, reject); }; } supported() { return "WebSocket" in (window || global); } reconnect(resolve, reject) { if (this.currentReconnectAttempts++ < this.options.maxReconnectAttempts) { setTimeout(() => { this.logger.debug("Reconnecting..."); this.openImpl(resolve, reject); }, this.options.autoReconnectInterval); } else { reject(); } } } exports.WS = WS; //# sourceMappingURL=ws.js.map