Skip to content

Commit

Permalink
chore: re-establish websocket connection upon connection close
Browse files Browse the repository at this point in the history
  • Loading branch information
karolsojko committed Dec 4, 2023
1 parent 72f4122 commit 5b35654
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions packages/services/src/Domain/Api/WebsocketsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { StorageServiceInterface } from '../Storage/StorageServiceInterface'
import { InternalEventBusInterface } from '../Internal/InternalEventBusInterface'
import { AbstractService } from '../Service/AbstractService'
import { StorageKey } from '../Storage/StorageKeys'
import { Result } from '@standardnotes/domain-core'

export class WebSocketsService extends AbstractService<WebSocketsServiceEvent, DomainEventInterface> {
private webSocket?: WebSocket
Expand Down Expand Up @@ -36,22 +37,24 @@ export class WebSocketsService extends AbstractService<WebSocketsServiceEvent, D
)._websocket_url
}

async startWebSocketConnection(): Promise<void> {
async startWebSocketConnection(): Promise<Result<void>> {
if (!this.webSocketUrl) {
return
return Result.fail('WebSocket URL is not set')
}

const webSocketConectionToken = await this.createWebSocketConnectionToken()
if (webSocketConectionToken === undefined) {
return
return Result.fail('Failed to create WebSocket connection token')
}

try {
this.webSocket = new WebSocket(`${this.webSocketUrl}?authToken=${webSocketConectionToken}`)
this.webSocket.onmessage = this.onWebSocketMessage.bind(this)
this.webSocket.onclose = this.onWebSocketClose.bind(this)
} catch (e) {
console.error('Error starting WebSocket connection', e)

return Result.ok()
} catch (error) {
return Result.fail(`Error starting WebSocket connection: ${(error as Error).message}`)
}
}

Expand Down Expand Up @@ -87,7 +90,9 @@ export class WebSocketsService extends AbstractService<WebSocketsServiceEvent, D
}

private onWebSocketClose() {
this.webSocket = undefined
if (this.webSocket?.readyState === WebSocket.CLOSED) {
void this.startWebSocketConnection()
}
}

private async createWebSocketConnectionToken(): Promise<string | undefined> {
Expand Down

0 comments on commit 5b35654

Please sign in to comment.