class Server { constructor(apiDataUrl, websocketUrl) { this.socketHandlers = []; this.apidataurl = apiDataUrl; this.websocketurl = websocketUrl; this.webSocket = null; } apiGet = (path) => { return new Promise((resolve, reject) => { var r = new XMLHttpRequest(); r.open("GET", this.apidataurl + path, true); r.onreadystatechange = function (response) { if (r.readyState == 4 && r.status == 200) { resolve(JSON.parse(r.responseText)); } if (r.readyState == 4 && r.status != 200) { reject(JSON.parse(r.response)); } return; } r.onerror = function (response) { console.error("onerror", response, r); reject(r.responseText); } r.setRequestHeader("Content-Type", "application/json"); r.send(); }); }; apiPost = (path, data) => { return new Promise((resolve, reject) => { var r = new XMLHttpRequest(); r.open("POST", this.apidataurl + path, true); r.onreadystatechange = function (response) { if (r.readyState == 4 && r.status == 200) { resolve(JSON.parse(r.responseText)); } if (r.readyState == 4 && r.status != 200) { reject(r.responseText); } return; } r.onerror = function (response) { console.error("onerror", response, r); reject(r.responseText); } r.setRequestHeader("Content-Type", "application/json"); let jsonData = JSON.stringify(data); r.send(jsonData); }); }; websocketConnect = () => { this.webSocket = new WebSocket(this.websocketurl); this.webSocket.onmessage = this.handleWebsocketMessage; this.webSocket.onopen = this.handleWebsocketOpen; this.webSocket.onclose = this.handleWebsocketClose; this.webSocket.onerror = this.handleWebsocketError; }; websocketSend = (message) => { try { this.ebSocket.send(message); } catch (error) { console.error("websocket", error); } }; attachWebsocketHandler = (handler) => { this.socketHandlers.push(handler); } removeWebsocketHandler = (handler) => { this.socketHandlers.splice(this.socketHandlers.indexOf(handler), 1); } handleWebsocketMessage = (event) => { this.socketHandlers.forEach(handler => { if(handler.hasOwnProperty("onmessage")){ handler.onmessage(event.data); } }) } handleWebsocketOpen = (event) => { this.socketHandlers.forEach(handler => { if(handler.hasOwnProperty("onopen")){ handler.onopen(event); } }) } handleWebsocketClose = (event) => { this.socketHandlers.forEach(handler => { if(handler.hasOwnProperty("onclose")){ handler.onclose(event); } }) } handleWebsocketError = (event) => { this.socketHandlers.forEach(handler => { if(handler.hasOwnProperty("onerror")){ handler.onerror(event); } }) } }