File size: 3,052 Bytes
4f9f661
 
 
79278ec
 
4f9f661
79278ec
4f9f661
 
 
 
79278ec
 
 
 
 
 
 
 
4f9f661
79278ec
 
 
 
 
 
4f9f661
79278ec
 
 
4f9f661
79278ec
 
 
 
4f9f661
 
 
 
 
79278ec
 
 
 
 
 
 
 
4f9f661
 
 
 
 
 
 
 
 
 
 
79278ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f9f661
79278ec
 
 
 
 
4f9f661
79278ec
 
 
4f9f661
 
79278ec
 
4f9f661
 
79278ec
 
 
 
 
4f9f661
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
43
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { apiBaseUrl } from '../constants';
import { queryClient } from '@/main';

export interface IAxiosParams {
  method: AxiosRequestConfig['method'];
  url: string;
  params?: AxiosRequestConfig['params'];
  data?: AxiosRequestConfig['data'];
  headers?: AxiosRequestConfig['headers'];
  responseType?: AxiosRequestConfig['responseType'];
  notCauseError?: boolean;
  signal?: AbortSignal;
}

export interface IQueryErrorResponse {
  error: {
    status: unknown;
    data: unknown;
    headers?: AxiosResponse['headers'];
    notCauseError?: boolean;
  };
}

export interface GenericIdentityFn<Type> {
  data: Type;
  headers?: AxiosResponse['headers'];
}

export const instance = axios.create({
  baseURL: apiBaseUrl ? `${apiBaseUrl}` : '',
  timeout: 600000,
});

const requestInterceptors = (req: InternalAxiosRequestConfig) => {
  // Добавляем jwt токен для всех маршрутов
  const token = localStorage.getItem('authToken');
  if (token) {
    req.headers.Authorization = `Bearer ${token}`;
  }
  return req;
};

const successInterceptors = (response: AxiosResponse) => response;

const errorInterceptors = async (error: AxiosError) => {
  const message = error.message;

  if (message.includes('409')) {
    console.log('409');
    queryClient.invalidateQueries({ queryKey: ['processing'] });
  }
  if (error.response?.status === 401) {
    localStorage.removeItem('authToken');
    window.location.href = '/login'; // Редирект на логин при 401
  } else {
    if (!axios.isCancel(error) && !message.includes('409')) {
      alert(`${message} Произошла ошибка`);
    }
  }
  return Promise.reject(error);
};

instance.interceptors.request.use(requestInterceptors);
instance.interceptors.response.use(successInterceptors, errorInterceptors);

export const query = async <T>(
  { url, signal, ...requestOptions }: IAxiosParams,
  baseUrl = apiBaseUrl
): Promise<GenericIdentityFn<T> | IQueryErrorResponse> => {
  const controller = new AbortController();
  const requestSignal = signal || controller.signal;

  try {
    console.log('Попытка отправки запроса');
    const result = await instance({
      url: `${baseUrl}${url}`,
      signal: requestSignal,
      ...requestOptions,
    });
    console.log('Запрос отправлен, результат:', result);
    return { data: result.data as T, headers: result.headers };
  } catch (axiosError) {
    if (axios.isCancel(axiosError)) {
      console.log('Запрос отменен');
      return { error: { status: 'Cancelled', data: 'Request was cancelled', notCauseError: true } };
    }
    const err = axiosError as AxiosError;
    console.log('Ошибка при отправке запроса');
    return { error: { status: err.response?.status, data: err.response?.data, headers: err.response?.headers } };
  } finally {
    if (!signal) {
      controller.abort();
    }
  }
};