requestUtils.ts 1.71 KB
Newer Older
Maxym Borodenko's avatar
Maxym Borodenko committed
1
2
import axios from 'axios';

3
4
5
6
7
8
9
10
import ApiError from 'model/ApiError';

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    return Promise.reject(ApiError.axiosError(error));
});

11
12
13
14
15
16
17
18
19
20
21
/**
 * Default Axios configuration for accessing the backend API
 */
export const axiosBackend = axios.create({
  baseURL: 'http://localhost:3000/proxy', // use embedded proxy
  timeout: 0,
  headers: {
    'X-Custom-Header': 'Genesys Frontend',
    'Content-Type': 'application/json',
  },
});
Maxym Borodenko's avatar
Maxym Borodenko committed
22

23
24
25
26
27
axiosBackend.interceptors.request.use((config) => {
  // Do something before request is sent
  console.log('Backend API request to ', config.url);
  return config;
}, (error) => {
28
  console.log('Backend error!!');
29
  // Do something with request error
30
  return Promise.reject(ApiError.axiosError(error));
31
32
33
34
35
36
37
});

/**
 * Configure axios instance used for backend API calls
 * @param apiUrl baseURL to the backend API (http://localhost:3000/proxy)
 * @param authToken OAuth authorization token
 */
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
38
export const configureBackendApi = ({apiUrl, accessToken, origin, timeout = 20000}: {apiUrl?: string, accessToken?: string, origin?: string, timeout?: number}) => {
39
40
41
  if (apiUrl) {
    console.log(`Using backend API baseURL ${apiUrl}`);
    axiosBackend.defaults.baseURL = apiUrl;
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
42
    console.log(`axiosBackend.defaults.headers`, axiosBackend.defaults.headers);
43
44
45
46
47
  }
  if (accessToken) {
    console.log(`Using backend API accessToken ..snip..`);
    axiosBackend.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
  }
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
48
49
50
51
  if (origin) {
    console.log(`Using origin ${origin}`);
    axiosBackend.defaults.headers.common.Origin = origin;
  }
52
53
54
  console.log(`Using backend API timeout ${timeout}`);
  axiosBackend.defaults.timeout = timeout;
};