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() } }