Skip to content

Instantly share code, notes, and snippets.

View oleh-zaporozhets's full-sized avatar

Oleh Zaporozhets oleh-zaporozhets

View GitHub Profile
...
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),
...
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);
}
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;
class UsefulService extends Http {
constructor() {
super('https://3rd-party.com/');
}
public getInfo() {
return this.instance.get('/useful-information');
}
}
import axios, { AxiosInstance } from 'axios';
class Http implements IHttp {
public readonly instance: AxiosInstance;
constructor(baseURL: string) {
this.instance = axios.create({ baseURL });
}
}
import Storage from './storage';
enum Locals {
ACCESS_TOKEN = 'access_token',
REFRESH_TOKEN = 'refresh_token'
}
export default class Tokens extends Storage<Locals> {
private static instance?: Tokens;
public clear() {
this.clearItems([Locals.ACCESS_TOKEN, Locals.REFRESH_TOKEN]);
}
public getRefreshToken() {
return this.get(Locals.REFRESH_TOKEN);
}
public setRefreshToken(refreshToken: string) {
this.set(Locals.REFRESH_TOKEN, refreshToken);
}
public getAccessToken() {
return this.get(Locals.ACCESS_TOKEN);
}
public setAccessToken(accessToken: string) {
this.set(Locals.ACCESS_TOKEN, accessToken);
}