mirror of
https://github.com/AmruthPillai/Reactive-Resume.git
synced 2025-11-15 01:01:43 +10:00
🚀 release v3.0.0
This commit is contained in:
55
client/services/axios.ts
Normal file
55
client/services/axios.ts
Normal file
@ -0,0 +1,55 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user