UNPKG

@bugtamer/async-status

Version:
1 lines 2.27 kB
"use strict";var State;Object.defineProperty(exports,"__esModule",{value:!0}),exports.AsyncStatus=void 0,function(State){State[State.noCalls=0]="noCalls",State[State.started=1]="started",State[State.done=2]="done",State[State.aborted=3]="aborted"}(State=State||{});class AsyncStatus{constructor(){this._attemptCount=0,this._successfulAttemptCount=0,this._failedAttemptCount=0,this._initialTime=0,this._finalTime=AsyncStatus.UNDEFINED_TIME,this._status=State.noCalls}start(){this._forbiddenStateGuard(this.isOngoing,AsyncStatus.startErrorMessage),this._overflowGuard(this._attemptCount),this._status=State.started,this._attemptCount++,this._initialTime=this._currentTime(),this._finalTime=AsyncStatus.UNDEFINED_TIME}end(){this._forbiddenStateGuard(this.isIdle,AsyncStatus.endErrorMessage),this._status=State.done,this._successfulAttemptCount++,this._finalTime=this._currentTime()}abort(){this._forbiddenStateGuard(this.isIdle,AsyncStatus.abortErrorMessage),this._status=State.aborted,this._failedAttemptCount++,this._finalTime=this._currentTime()}resetAttemptStats(){this._attemptCount=0,this._successfulAttemptCount=0,this._failedAttemptCount=0}get isIdle(){return this._status!==State.started}get isOngoing(){return this._status===State.started}get wasSuccessful(){return this._status===State.done}get wasFailed(){return this._status===State.aborted}get elapsedTime(){return this._status===State.noCalls?AsyncStatus.UNDEFINED_TIME:this._status===State.started?this._currentTime()-this._initialTime:this._finalTime-this._initialTime}get attempts(){return this._attemptCount}get successfulAttempts(){return this._successfulAttemptCount}get failedAttempts(){return this._failedAttemptCount}_currentTime(){return Date.now()}_forbiddenStateGuard(isAnIllegalState,errorMessage){if(isAnIllegalState)throw new Error(errorMessage)}_overflowGuard(currentCount){if(currentCount===Number.MAX_SAFE_INTEGER)throw new Error(AsyncStatus.overflowErrorMessage)}}(exports.AsyncStatus=AsyncStatus).UNDEFINED_TIME=-1,AsyncStatus.startErrorMessage="'start()' cannot be called in 'started' state.",AsyncStatus.endErrorMessage="'end()' cannot be called in 'idle' state.",AsyncStatus.abortErrorMessage="'abort()' cannot be called in 'idle' state.",AsyncStatus.overflowErrorMessage="Overflow error.";