rainbox.email/assets/ts/PersistentWebSocket.ts

40 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-09-23 13:30:48 +02:00
export default class PersistentWebsocket {
private webSocket?: WebSocket;
public constructor(
protected readonly url: string,
private readonly handler: MessageHandler,
protected readonly reconnectOnClose: boolean = true,
) {
}
2020-10-05 13:38:03 +02:00
public run(): void {
const _webSocket = this.webSocket = new WebSocket(this.url);
this.webSocket.addEventListener('open', () => {
2020-09-23 13:30:48 +02:00
console.debug('Websocket connected');
});
this.webSocket.addEventListener('message', (e) => {
2020-10-05 13:38:03 +02:00
this.handler(_webSocket, e);
2020-09-23 13:30:48 +02:00
});
this.webSocket.addEventListener('error', (e) => {
console.error('Websocket error', e);
});
this.webSocket.addEventListener('close', (e) => {
this.webSocket = undefined;
console.debug('Websocket closed', e.code, e.reason);
if (this.reconnectOnClose) {
setTimeout(() => this.run(), 1000);
}
});
}
2020-10-05 13:38:03 +02:00
public send(data: string): void {
2020-09-23 13:30:48 +02:00
if (!this.webSocket) throw new Error('WebSocket not connected');
this.webSocket.send(data);
}
}
export type MessageHandler = (webSocket: WebSocket, e: MessageEvent) => void;