requestUtils.ts 2.09 KB
Newer Older
1
2
import axios from 'axios';

3
4
import { ApiError } from '@gringlobal/client/model/common';
import { clearCookies } from '@gringlobal/client/utilities';
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

/**
 * Generate API prefix when a language is selected
 * @param lang Current language ('en', 'de', ...)
 */
export const apiLanguage = (lang: string) => lang === 'en' ? '' : `/${lang}`;

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

/**
 * Default Axios configuration for accessing the backend API
 */
export const axiosBackend = axios.create({
  baseURL: process.env.API_URL, // use embedded proxy
  timeout: 0,
  withCredentials: true,
  headers: {
    'X-Custom-Header': 'Grin global client',
    'Content-Type': 'application/json',
  },
});


axiosBackend.interceptors.response.use(
  (config) => config,
  (error) => {
    console.log('Backend error!! Error', error);

    if (axios.isCancel(error)) {
      throw error;
    }

    if (error.response && error.response.status === 401 && error.response.data.error === 'invalid_token') {
      console.log('Error on 401, invalid token: ', error);
      clearCookies();
      window.location.replace('/');
    }

Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
43
    throw error;
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  },
);

/**
 * Configure axios instance used for backend API calls
 * @param apiUrl baseURL to the backend API
 * @param authToken OAuth authorization token
 */
export const configureBackendApi = ({ apiUrl, accessToken, origin, timeout }: { apiUrl?: string, accessToken?: string, origin?: string, timeout?: number }) => {
  if (apiUrl) {
    console.log(`Using backend API baseURL ${apiUrl}`);
    axiosBackend.defaults.baseURL = apiUrl;
    console.log('axiosBackend.defaults.headers', axiosBackend.defaults.headers);
  }
  if (accessToken) {
    console.log('Using backend API accessToken ..snip..');
    axiosBackend.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
  }
  if (origin) {
    console.log(`Using origin ${origin}`);
    axiosBackend.defaults.headers.common.Origin = origin;
  }
  if (timeout) {
    console.log(`Using backend API timeout ${timeout}`);
    axiosBackend.defaults.timeout = timeout;
  }
};