UNPKG

camstreamerlib

Version:

Helper library for CamStreamer ACAP applications.

63 lines (62 loc) 1.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WsClient = void 0; const REFRESH_TIMEOUT = 5_000; class WsClient { getUrl; getAuthToken; isDestroyed = false; ws = null; restartTimeout = null; constructor(getUrl, getAuthToken) { this.getUrl = getUrl; this.getAuthToken = getAuthToken; } init() { if (this.isDestroyed) { return; } this.destroyWebsocket(); const ws = new WebSocket(this.getUrl(), 'events'); ws.onopen = async () => { try { const token = await this.getAuthToken(); ws.send(JSON.stringify({ authorization: token })); } catch (error) { console.error('Error sending auth token:', error); ws.close(); } }; ws.onmessage = (e) => this.onmessage(e); ws.onclose = () => { this.restartTimeout = setTimeout(() => this.init(), REFRESH_TIMEOUT); }; this.ws = ws; } send = (msg) => { this.ws?.send(msg); }; onmessage = (_) => { }; destroy = () => { this.isDestroyed = true; this.destroyWebsocket(); }; destroyWebsocket() { if (this.restartTimeout) { clearTimeout(this.restartTimeout); this.restartTimeout = null; } if (!this.ws) { return; } this.ws.onmessage = null; this.ws.onopen = null; this.ws.onclose = null; if (this.ws.readyState === this.ws.OPEN) { this.ws.close(); } this.ws = null; } } exports.WsClient = WsClient;