UNPKG

@fraserdarwent/xapi-node

Version:

This project is made possible to get data from Forex market, execute market or limit order with NodeJS/JS through WebSocket connection

107 lines 3.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebSocketWrapper = exports.isNodeJS = void 0; const Listener_1 = require("./Listener"); const Timer_1 = require("./Timer"); exports.isNodeJS = () => typeof window === 'undefined' && typeof module !== 'undefined' && module.exports; class WebSocketWrapper extends Listener_1.Listener { constructor(url, tryReconnectOnFail = true) { super(); this.ws = null; this._status = false; this._tryReconnect = false; this._connectionTimeout = new Timer_1.Timer(); this.url = url; this._tryReconnect = tryReconnectOnFail; this.onOpen(() => { this._connectionTimeout.clear(); }); this.onClose(() => { if (this._tryReconnect) { this._connectionTimeout.setTimeout(() => { if (this._tryReconnect) { this.connect(); } }, 3000); } }); } connect() { this._connectionTimeout.clear(); if (exports.isNodeJS()) { const WebSocketClient = require('ws'); this.ws = new WebSocketClient(this.url); this.ws.on('open', () => { this._status = true; this.callListener('ws_open'); }); this.ws.on('close', () => { this._status = false; this.callListener('ws_close'); }); this.ws.on('message', (message) => { this.callListener('ws_message', [message]); }); this.ws.on('error', (error) => { this.callListener('ws_error', [error]); }); } else { this.ws = new WebSocket(this.url); this.ws.onopen = () => { if (this._status === false) { this._status = true; this.callListener('ws_statusChange', [true]); } this.callListener('ws_open'); }; this.ws.onclose = () => { if (this._status) { this._status = false; this.callListener('ws_statusChange', [false]); } this.callListener('ws_close'); }; this.ws.onmessage = (event) => { this.callListener('ws_message', [event.data]); }; this.ws.onerror = (error) => { this.callListener('ws_error', [error]); }; } } get status() { return this._status; } onStatusChange(callback) { this.addListener('ws_statusChange', callback); } onOpen(callback) { this.addListener('ws_open', callback); } onMessage(callback) { this.addListener('ws_message', callback); } onError(callback) { this.addListener('ws_error', callback); } onClose(callback) { this.addListener('ws_close', callback); } send(data) { if (this.status) { this.ws.send(data); return Promise.resolve(); } else { return Promise.reject(this.url + ' websocket is not connected'); } } close() { this._connectionTimeout.clear(); this._tryReconnect = false; this.ws && this.ws.close(); } } exports.WebSocketWrapper = WebSocketWrapper; //# sourceMappingURL=WebSocketWrapper.js.map