neko/src/component/internal/websocket.ts

119 lines
3.0 KiB
TypeScript
Raw Normal View History

2020-11-06 05:15:21 +13:00
import EventEmitter from 'eventemitter3'
import { Logger } from '../utils/logger'
2021-02-09 07:14:39 +13:00
export const connTimeout = 15000
export const reconnInterval = 1000
2020-11-06 05:15:21 +13:00
export interface NekoWebSocketEvents {
connecting: () => void
connected: () => void
disconnected: (error?: Error) => void
message: (event: string, payload: any) => void
2020-11-06 05:15:21 +13:00
}
export class NekoWebSocket extends EventEmitter<NekoWebSocketEvents> {
private _ws?: WebSocket
private _log: Logger
constructor() {
super()
2020-11-06 05:20:37 +13:00
2020-11-06 05:15:21 +13:00
this._log = new Logger('websocket')
}
2021-01-30 08:13:37 +13:00
get supported() {
return typeof WebSocket !== 'undefined' && WebSocket.OPEN === 1
}
2020-11-06 05:15:21 +13:00
get connected() {
return typeof this._ws !== 'undefined' && this._ws.readyState === WebSocket.OPEN
}
public async connect(url: string) {
if (!this.supported) {
throw new Error('browser does not support websockets')
}
2020-11-06 05:15:21 +13:00
if (this.connected) {
throw new Error('attempting to create websocket while connection open')
}
if (typeof this._ws !== 'undefined') {
this._log.debug(`previous websocket connection needs to be closed`)
this.disconnect()
}
2021-05-10 07:06:09 +12:00
await new Promise<void>((res, rej) => {
this._ws = new WebSocket(url)
2021-05-10 07:06:09 +12:00
this._log.info(`connecting`)
this.emit('connecting')
2020-11-06 05:15:21 +13:00
2021-05-10 07:06:09 +12:00
this._ws.onclose = rej.bind(this, new Error('connection close'))
this._ws.onerror = rej.bind(this, new Error('connection error'))
this._ws.onmessage = this.onMessage.bind(this)
2020-11-06 05:15:21 +13:00
let timeout = window.setTimeout(rej.bind(this, new Error('connection timeout')), connTimeout)
2021-05-10 07:06:09 +12:00
this._ws.onopen = () => {
window.clearTimeout(timeout)
this._ws!.onclose = this.onDisconnected.bind(this, 'close')
this._ws!.onerror = this.onDisconnected.bind(this, 'error')
2021-05-10 07:06:09 +12:00
this.onConnected()
res()
}
})
2020-11-06 05:15:21 +13:00
}
public disconnect() {
if (typeof this._ws !== 'undefined') {
// unmount all events
this._ws.onopen = () => {}
this._ws.onclose = () => {}
this._ws.onerror = () => {}
this._ws.onmessage = () => {}
2020-11-06 05:15:21 +13:00
try {
this._ws.close()
2020-11-06 05:15:21 +13:00
} catch (err) {}
this._ws = undefined
}
}
public send(event: string, payload?: any) {
if (!this.connected) {
this._log.warn(`attempting to send message while disconnected`)
return
}
2020-11-06 05:20:37 +13:00
2020-11-06 05:15:21 +13:00
this._log.debug(`sending event '${event}' ${payload ? `with payload: ` : ''}`, payload)
this._ws!.send(JSON.stringify({ event, ...payload }))
}
private onMessage(e: MessageEvent) {
const { event, ...payload } = JSON.parse(e.data)
this._log.debug(`received websocket event ${event} ${payload ? `with payload: ` : ''}`, payload)
this.emit('message', event, payload)
2020-11-06 05:15:21 +13:00
}
private onConnected() {
if (!this.connected) {
this._log.warn(`onConnected called while being disconnected`)
return
}
2021-01-16 05:17:49 +13:00
this._log.info(`connected`)
2020-11-06 05:15:21 +13:00
this.emit('connected')
}
private onDisconnected(reason: string) {
this.disconnect()
2021-02-09 07:14:39 +13:00
this._log.info(`connection ${reason}`)
this.emit('disconnected', new Error(`connection ${reason}`))
2020-11-06 05:15:21 +13:00
}
}