mirror of
https://github.com/AmruthPillai/Reactive-Resume.git
synced 2025-11-13 00:03:27 +10:00
56 lines
1.1 KiB
TypeScript
56 lines
1.1 KiB
TypeScript
import _axios, { AxiosError } from 'axios';
|
|
import Router from 'next/router';
|
|
|
|
import { logout } from '@/store/auth/authSlice';
|
|
|
|
import store from '../store';
|
|
|
|
export type ServerError = {
|
|
statusCode: number;
|
|
message: string;
|
|
timestamp: string;
|
|
path: string;
|
|
};
|
|
|
|
const axios = _axios.create({
|
|
baseURL: `${process.env.serverUrl}/api`,
|
|
});
|
|
|
|
export const uninterceptedAxios = _axios.create({
|
|
baseURL: `${process.env.serverUrl}/api`,
|
|
});
|
|
|
|
axios.interceptors.request.use((config) => {
|
|
const { accessToken } = store.getState().auth;
|
|
|
|
config.headers = {
|
|
...config.headers,
|
|
Authorization: `Bearer ${accessToken}`,
|
|
};
|
|
|
|
return config;
|
|
});
|
|
|
|
axios.interceptors.response.use(
|
|
(response) => response,
|
|
(error: AxiosError) => {
|
|
const { response } = error;
|
|
|
|
if (response) {
|
|
const errorObject: ServerError = response.data;
|
|
const code = errorObject.statusCode;
|
|
|
|
if (code === 401 || code === 404) {
|
|
store.dispatch(logout());
|
|
Router.push('/');
|
|
}
|
|
|
|
throw errorObject;
|
|
}
|
|
|
|
throw error;
|
|
}
|
|
);
|
|
|
|
export default axios;
|