mirror of
https://github.com/smartyellow/status.git
synced 2024-11-22 18:57:47 +01:00
41 lines
870 B
JavaScript
41 lines
870 B
JavaScript
import { ringBell } from './lib';
|
|
|
|
const socketUrl = window.location.href.replace('http', 'ws') + '/socket';
|
|
let reconnectAttempts = 0;
|
|
let ws;
|
|
|
|
export async function connect({ onData }) {
|
|
ws = new WebSocket(socketUrl);
|
|
|
|
ws.onmessage = async evt => {
|
|
const data = JSON.parse(evt.data || 'false');
|
|
|
|
switch (data.cmd) {
|
|
case 'data':
|
|
onData(data);
|
|
break;
|
|
|
|
case 'bell':
|
|
ringBell();
|
|
break;
|
|
|
|
default:
|
|
break;
|
|
}
|
|
};
|
|
|
|
ws.onopen = () => {
|
|
if (reconnectAttempts) {
|
|
window.location.reload();
|
|
}
|
|
};
|
|
|
|
ws.onclose = async () => {
|
|
console.error(`Websocket closed, trying to reconnect... (#${reconnectAttempts++})`);
|
|
await new Promise(res => setTimeout(res, reconnectAttempts * 500));
|
|
await connect({ onData });
|
|
};
|
|
|
|
ws.onerror = err => console.error('Connection error', err);
|
|
}
|