Skip to content

Instantly share code, notes, and snippets.

@iampato
Last active September 26, 2023 08:37
Show Gist options
  • Save iampato/43173e3a0ef4d5b1bd72144af9f0f9c2 to your computer and use it in GitHub Desktop.
Save iampato/43173e3a0ef4d5b1bd72144af9f0f9c2 to your computer and use it in GitHub Desktop.
Custom axios http client
/*
* Copyright (c) 2023
* All rights reserved. @Patrick Waweru
*/
import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import {destory, getAccessToken} from './SharePreference';
import {AppConstants} from './Constants';
export class HttpClient {
private axiosInstance?: AxiosInstance;
private static instance: HttpClient;
constructor() {
this.setupAxios();
this.setupInterceptors();
}
public static getInstance(): HttpClient {
if (!HttpClient.instance) {
HttpClient.instance = new HttpClient();
}
return HttpClient.instance;
}
private setupAxios() {
this.axiosInstance = axios.create({
baseURL: AppConstants.apiBaseUrl, // https://localhost:9001/api
timeout: 10000,
});
}
private setupInterceptors(): void {
// Request interceptor
this.axiosInstance?.interceptors.request.use(
async config => {
// Modify request config here if needed
// e.g., add headers, tokens, etc.
const token = await getAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
},
);
// Response interceptor
this.axiosInstance?.interceptors.response.use(
(response: AxiosResponse) => {
return response;
},
error => {
if (error.response.status === 401) {
// refresh token
} else {
return Promise.reject(error);
}
},
);
}
private refreshToken(refreshToken: string): Promise<string> {
// Make a request to the /refresh endpoint with the refresh token
// Return a Promise that resolves with the new access token
return this.axiosInstance!.post('/refresh', {refreshToken}).then(
response => response.data.accessToken,
);
}
public get(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse> {
return this.axiosInstance!.get(url, config);
}
public post(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<AxiosResponse> {
return this.axiosInstance!.post(url, data, config);
}
public put(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<AxiosResponse> {
return this.axiosInstance!.put(url, data, config);
}
public patch(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<AxiosResponse> {
return this.axiosInstance!.patch(url, data, config);
}
public delete(
url: string,
config?: AxiosRequestConfig,
): Promise<AxiosResponse> {
return this.axiosInstance!.delete(url, config);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment