Connect to VaaS * @throws {VaasAuthenticationError} Authentication failed. * @throws {VaasConnectionClosedError} Connection was closed. Call connect() to reconnect.
(token: string, url = VAAS_URL)
| 295 | * @throws {VaasConnectionClosedError} Connection was closed. Call connect() to reconnect. |
| 296 | */ |
| 297 | public connect(token: string, url = VAAS_URL): Promise<void> { |
| 298 | return new Promise((resolve, reject) => { |
| 299 | const ws = this.webSocketFactory(url); |
| 300 | this.connection = { ws: ws }; |
| 301 | this.closeEvent = undefined; |
| 302 | this.authenticationError = undefined; |
| 303 | this.pingTimeout = undefined; |
| 304 | |
| 305 | // ws library does not have auto-keepalive |
| 306 | // https://github.com/websockets/ws/issues/767 |
| 307 | if (ws.on !== undefined) { |
| 308 | ws.on("ping", (payload) => { |
| 309 | ws.pong(payload); |
| 310 | }); |
| 311 | ws.on("pong", () => { |
| 312 | this.pingTimeout = setTimeout(() => ws.ping(), 10000); |
| 313 | }); |
| 314 | } |
| 315 | ws.onopen = () => { |
| 316 | try { |
| 317 | this.authenticate(token); |
| 318 | } catch (error) { |
| 319 | reject(error); |
| 320 | } |
| 321 | }; |
| 322 | ws.onclose = (event) => { |
| 323 | if (this.pingTimeout) { |
| 324 | clearTimeout(this.pingTimeout); |
| 325 | this.pingTimeout = undefined; |
| 326 | } |
| 327 | if (!event.wasClean) { |
| 328 | this.closeEvent = event; |
| 329 | } |
| 330 | const reason = new VaasConnectionClosedError(event); |
| 331 | if (this.verdictPromises.size > 0) { |
| 332 | this.verdictPromises.forEach((c) => c.reject(reason)); |
| 333 | this.verdictPromises.clear(); |
| 334 | } |
| 335 | reject(reason); |
| 336 | }; |
| 337 | ws.onmessage = async (event) => { |
| 338 | const message = defaultSerializer.deserializeObject( |
| 339 | event.data, |
| 340 | Message, |
| 341 | ) as Message; |
| 342 | |
| 343 | switch (message.kind) { |
| 344 | case Kind.AuthResponse: |
| 345 | const authResponse = defaultSerializer.deserializeObject( |
| 346 | event.data, |
| 347 | AuthenticationResponse, |
| 348 | ) as AuthenticationResponse; |
| 349 | if (authResponse.success) { |
| 350 | this.connection!.sessionId = authResponse.session_id; |
| 351 | resolve(); |
| 352 | return; |
| 353 | } |
| 354 | this.authenticationError = authResponse; |
no test coverage detected