Created
January 3, 2025 15:44
-
-
Save justgeek/8a120448660b2e8e9d168ec37b325afc 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 axios, { AxiosInstance, AxiosRequestConfig } from 'axios'; | |
import { getSession, signOut } from 'next-auth/react'; | |
import { Session } from '../api/auth/auth.types'; | |
import { routes } from '../routes'; | |
class AxiosProvider { | |
private axiosInstance: AxiosInstance; | |
constructor() { | |
this.axiosInstance = axios.create({ | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
}); | |
this.initializeRequestInterceptor(); | |
this.initializeResponseInterceptor(); | |
} | |
private async initializeRequestInterceptor() { | |
const session = (await getSession()) as Session; | |
const token = session?.jwtPayload; | |
this.axiosInstance.interceptors.request.use( | |
(config) => { | |
if (token) { | |
config.headers.Authorization = `Bearer ${token}`; | |
} | |
return config; | |
}, | |
async (error) => { | |
const errorMessage = this.handleErrorByStatus(error?.response?.status || -1); | |
return Promise.reject(errorMessage); | |
} | |
); | |
} | |
private initializeResponseInterceptor() { | |
this.axiosInstance.interceptors.response.use( | |
(response) => response, | |
async (error) => { | |
const errorMessage = this.handleErrorByStatus(error?.response?.status || -1); | |
let newError; | |
try { | |
const alternateErrorMessage = error?.response?.data?.message; | |
const errorOptions: ErrorOptions | undefined = alternateErrorMessage | |
? { | |
cause: alternateErrorMessage, | |
} | |
: undefined; | |
newError = new Error(errorMessage, errorOptions); | |
} catch (_e) { | |
newError = new Error(errorMessage); | |
} | |
return Promise.reject(newError); | |
} | |
); | |
} | |
public async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> { | |
return this.axiosInstance.get<T>(url, config).then((response) => response.data); | |
} | |
public async post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> { | |
return this.axiosInstance.post<T>(url, data, config).then((response) => response.data); | |
} | |
public async put<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> { | |
return this.axiosInstance.put<T>(url, data, config).then((response) => response.data); | |
} | |
public async patch<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> { | |
return this.axiosInstance.patch<T>(url, data, config).then((response) => response.data); | |
} | |
public async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> { | |
return this.axiosInstance.delete<T>(url, config).then((response) => response.data); | |
} | |
private handleErrorByStatus(errorStatusCode: number) { | |
let message = ''; | |
let shouldLogOutUser = false; | |
switch (errorStatusCode) { | |
case -1: | |
message = 'Connection Timeout'; | |
break; | |
case 0: | |
message = 'Connection Error!'; | |
break; | |
case 400: | |
message = 'Bad Request. Please try again later.'; | |
break; | |
case 401: | |
message = 'Unauthorized Access, please login again'; | |
shouldLogOutUser = true; | |
break; | |
case 403: | |
message = 'Access Rejected'; | |
break; | |
case 404: | |
message = 'Not Found!'; | |
break; | |
case 500: | |
message = 'An error occurred on our side, please try again later'; | |
break; | |
default: | |
message = 'Something went wrong, try again later.'; | |
break; | |
} | |
if (shouldLogOutUser) { | |
signOut({ callbackUrl: routes.signIn.path }); | |
} | |
return message; | |
} | |
} | |
export const axiosProvider = new AxiosProvider(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment