Created
October 23, 2021 18:52
-
-
Save oleh-zaporozhets/b80b56c6ef35dcda4c13c18565c5c1b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; | |
class CircuitBreaker implements ICircuitBreaker { | |
private readonly http: IHttp; | |
private readonly timeout: number; | |
private isOpen = false; | |
private errorHandler: (error: any) => boolean; | |
constructor(http: IHttp, options: ICircuitBreakerOptions) { | |
this.http = http; | |
this.timeout = options.timeout; | |
this.errorHandler = options.errorHandler; | |
this.http.instance.interceptors.request.use(this.interceptRequest.bind(this)); | |
this.http.instance.interceptors.response.use( | |
(response: AxiosResponse) => response, | |
this.interceptErrorResponse.bind(this), | |
); | |
} | |
public getStatus() { | |
return this.isOpen; | |
} | |
private interceptRequest(config: AxiosRequestConfig) { | |
const CancelToken = axios.CancelToken; | |
const cancelToken = new CancelToken((cancel) => cancel('Circuit breaker is open')); | |
return { | |
...config, | |
...(this.isOpen ? { cancelToken } : {}), | |
}; | |
} | |
private interceptErrorResponse(error: any) { | |
const shouldCircuitBreakerBeOpen = this.errorHandler(error); | |
if (shouldCircuitBreakerBeOpen && !this.isOpen) { | |
this.openCircuitBreaker(); | |
} | |
return Promise.reject(error); | |
} | |
private openCircuitBreaker() { | |
this.isOpen = true; | |
setTimeout(() => { | |
this.isOpen = false; | |
}, this.timeout); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment