From cff7bcf373a84f00450f07ef0187085f8b2ebc06 Mon Sep 17 00:00:00 2001 From: Brendan Lane Date: Sat, 19 Dec 2020 03:10:21 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=BB=20TransactionHub=20almost=20done?= =?UTF-8?q?=20(Sync=20with=20local)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/modules/TransactionHub.ts | 53 ++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/src/modules/TransactionHub.ts b/src/modules/TransactionHub.ts index 03a3ffc..03bd762 100644 --- a/src/modules/TransactionHub.ts +++ b/src/modules/TransactionHub.ts @@ -1,11 +1,17 @@ +/* eslint-disable @typescript-eslint/no-floating-promises */ + // SpookVooper API - modules/TransactionHub.ts // Written by Brendan Lane - https://brndnln.dev/ -// import { Observable } from 'rxjs' +import { Observable } from 'rxjs' import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr' import { ReturnedTransaction } from './interfaces/Interfaces' const URI = 'https://spookvooper.com/transactionHub' +const retryTime = 5 +const retryTimeMS = retryTime * 1000 + +const fancy = true class TransactionHub { private readonly connection = new HubConnectionBuilder() @@ -14,19 +20,58 @@ class TransactionHub { .configureLogging(LogLevel.Information) .build() - public event - private val: ReturnedTransaction public fromAccount: string public toAccount: string - constructor () { + public event = new Observable((observer) => { this.connection.on('NotifyTransaction', (recieved: string) => { this.val = JSON.parse(recieved) this.fromAccount = this.val.FromAccount this.toAccount = this.val.ToAccount + + observer.next(this.val) }) + }) + + constructor () { + this.connection.onclose(function (e: any): void { + this.onClosed(e) + }) + } + + public async start (): Promise { + console.log(`[TransactionHub] Starting connection between local and ${URI}`) + + try { + await this.connection.start() + console.log('[TransactionHub] Connected!') + } catch (e) { + if (fancy) { + console.log('--------------------------------') + } + console.error('[TransactionHub] Error: Connection failed while trying to establish a connection\n', e) + if (fancy) { + console.log('--------------------------------') + } + console.log(`[TransactionHub] Retrying in ${retryTime} seconds`) + setTimeout(() => { + this.start() + }, retryTimeMS) + } + } + + private async onClosed (e: any): Promise { + if (fancy) { + console.log('--------------------------------') + } + console.error('[TransactionHub] Error: Connection closed unexpectedly', e) + if (fancy) { + console.log('--------------------------------') + } + + await this.start() } }