fchat-rising/chat/WebSocket.ts

47 lines
1.4 KiB
TypeScript
Raw Normal View History

2018-01-06 17:14:21 +01:00
import {WebSocketConnection} from '../fchat';
2020-07-05 12:43:27 -05:00
import log from 'electron-log'; //tslint:disable-line:match-default-export-name
2017-09-02 03:50:31 +02:00
export default class Socket implements WebSocketConnection {
2019-06-07 14:31:42 -05:00
static host = 'wss://chat.f-list.net/chat2';
2018-01-06 17:14:21 +01:00
private socket: WebSocket;
private lastHandler: Promise<void> = Promise.resolve();
2017-09-02 03:50:31 +02:00
constructor() {
this.socket = new WebSocket(Socket.host);
}
2019-01-03 18:38:17 +01:00
get readyState(): WebSocketConnection.ReadyState {
return this.socket.readyState;
}
2017-09-02 03:50:31 +02:00
close(): void {
2020-07-05 12:43:27 -05:00
log.debug('socket.close');
2017-09-02 03:50:31 +02:00
this.socket.close();
}
onMessage(handler: (message: string) => void): void {
2018-01-06 17:14:21 +01:00
this.socket.addEventListener('message', (e) => {
2018-08-10 18:59:37 +02:00
this.lastHandler = this.lastHandler.then(() => handler(<string>e.data), (err) => {
window.requestAnimationFrame(() => { throw err; });
handler(<string>e.data);
});
2018-01-06 17:14:21 +01:00
});
2017-09-02 03:50:31 +02:00
}
onOpen(handler: () => void): void {
this.socket.addEventListener('open', handler);
}
2020-06-30 11:46:38 -05:00
onClose(handler: (e: CloseEvent) => void): void {
2017-09-02 03:50:31 +02:00
this.socket.addEventListener('close', handler);
}
onError(handler: (error: Error) => void): void {
2018-04-11 21:17:58 +02:00
this.socket.addEventListener('error', () => handler(new Error()));
2017-09-02 03:50:31 +02:00
}
send(message: string): void {
this.socket.send(message);
}
2020-06-30 11:46:38 -05:00
}