From 3b04ed06d296ccf6820d840735c765374ebe4615 Mon Sep 17 00:00:00 2001 From: Andrey Platov Date: Wed, 11 Aug 2021 21:12:52 +0200 Subject: [PATCH] client reconnecting Signed-off-by: Andrey Platov --- plugins/client-resources/src/connection.ts | 40 +++++++++++++++------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/plugins/client-resources/src/connection.ts b/plugins/client-resources/src/connection.ts index 66a6af3fe9..82e830f7e0 100644 --- a/plugins/client-resources/src/connection.ts +++ b/plugins/client-resources/src/connection.ts @@ -31,11 +31,16 @@ class DeferredPromise { } class Connection implements Storage { + private websocket: WebSocket | null = null private readonly requests = new Map() private lastId = 0 - constructor (private readonly webSocket: WebSocket, private readonly handler: TxHander) { - this.webSocket.onmessage = (event: MessageEvent) => { + constructor (private readonly url: string, private readonly handler: TxHander) { + } + + private async openConnection (): Promise { + const websocket = new WebSocket(this.url) + websocket.onmessage = (event: MessageEvent) => { const resp = readResponse(event.data) if (resp.id !== undefined) { const promise = this.requests.get(resp.id) @@ -53,21 +58,36 @@ class Connection implements Storage { } const interval = setInterval(() => { // eslint-disable-next-line @typescript-eslint/no-floating-promises + console.log('ping') this.sendRequest('ping') }, 10000) - this.webSocket.onclose = () => { console.log('client websocket closed'); clearInterval(interval) } + websocket.onclose = () => { + console.log('client websocket closed') + clearInterval(interval) + this.websocket = null + } + return new Promise((resolve, reject) => { + websocket.onopen = () => { + resolve(websocket) + } + websocket.onerror = (event) => { + console.log('client websocket error', event) + reject(new Error('websocket error')) + } + }) } - private sendRequest (method: string, ...params: any[]): Promise { + private async sendRequest (method: string, ...params: any[]): Promise { + if (this.websocket === null) { this.websocket = await this.openConnection() } const id = this.lastId++ - this.webSocket.send(serialize({ + this.websocket.send(serialize({ method, params, id })) const promise = new DeferredPromise() this.requests.set(id, promise) - return promise.promise + return await promise.promise } findAll(_class: Ref>, query: DocumentQuery, options?: FindOptions): Promise> { @@ -80,11 +100,5 @@ class Connection implements Storage { } export async function connect (url: string, handler: TxHander): Promise { - return await new Promise((resolve, reject) => { - const webSocket = new WebSocket(url) - webSocket.onopen = () => { - resolve(new Connection(webSocket, handler)) - } - webSocket.onerror = () => reject(new Error('Could not connect')) - }) + return new Connection(url, handler) }