forked from alan2207/bulletproof-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-client.ts
42 lines (35 loc) · 1.08 KB
/
api-client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import Axios, { InternalAxiosRequestConfig } from 'axios';
import { useNotifications } from '@/components/ui/notifications';
import { env } from '@/config/env';
import { paths } from '@/config/paths';
function authRequestInterceptor(config: InternalAxiosRequestConfig) {
if (config.headers) {
config.headers.Accept = 'application/json';
}
config.withCredentials = true;
return config;
}
export const api = Axios.create({
baseURL: env.API_URL,
});
api.interceptors.request.use(authRequestInterceptor);
api.interceptors.response.use(
(response) => {
return response.data;
},
(error) => {
const message = error.response?.data?.message || error.message;
useNotifications.getState().addNotification({
type: 'error',
title: 'Error',
message,
});
if (error.response?.status === 401) {
const searchParams = new URLSearchParams();
const redirectTo =
searchParams.get('redirectTo') || window.location.pathname;
window.location.href = paths.auth.login.getHref(redirectTo);
}
return Promise.reject(error);
},
);