Created
May 15, 2019 21:12
-
-
Save rightisleft/be357fccdc1f5f7da5508da19d0f2d67 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {sleep} from "./sleep"; | |
const RETRY_COUNT: number = 1000; | |
const RETRY_DELAY_INCREASE: number = 500; | |
export class ConnectionRetry { | |
private _isConnected: boolean = false; | |
private _connectionAttempts: number = 0; | |
private _retryDelay: number = 0; | |
constructor(public connectable: IConnectable, public serviceName: string) { | |
} | |
public async init(): Promise<IConnectable> { | |
this._isConnected = await this.connect(); | |
while (!this._isConnected) { | |
await this.init(); | |
} | |
return this.connectable; | |
} | |
public async connect(): Promise<boolean> { | |
await sleep(this._retryDelay += RETRY_DELAY_INCREASE); | |
if (!this.isConnected && this._connectionAttempts < RETRY_COUNT) { | |
this._connectionAttempts++; | |
try { | |
console.log(`Service ${this.serviceName}: Making attempt ` + (this._connectionAttempts) + ` to connect...`); | |
return await this.connectable.establish(); | |
} catch (e) { | |
console.error(`Cannot establish connection with ${this.serviceName}`, e); | |
return false; | |
} | |
} else if (this.isConnected === false && RETRY_COUNT) { | |
console.error(`Failed: Could not establish connection to ${this.serviceName} after ${RETRY_COUNT} attempts.`); | |
return false; | |
} | |
} | |
public get isConnected(): boolean { | |
return this._isConnected; | |
} | |
} | |
export interface IConnectable { | |
start(): Promise<IConnectable>; | |
establish: () => Promise<boolean>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment