|
| 1 | +import type { HttpRequestConfigOverrides } from './types'; |
| 2 | +import type { AxiosRequestConfig } from 'axios'; |
| 3 | + |
| 4 | +import { DialogService, Toast } from '@laser-ui/components'; |
| 5 | +import { useUnmount } from '@laser-ui/hooks'; |
| 6 | +import { useRef } from 'react'; |
| 7 | +import { useTranslation } from 'react-i18next'; |
| 8 | +import { useLocation, useNavigate } from 'react-router'; |
| 9 | + |
| 10 | +import { axios } from './axios'; |
| 11 | +import { LOGIN_PATH, PREV_ROUTE_KEY } from '../../configs/router'; |
| 12 | + |
| 13 | +export function useAxios() { |
| 14 | + const location = useLocation(); |
| 15 | + const navigate = useNavigate(); |
| 16 | + const { t } = useTranslation(); |
| 17 | + |
| 18 | + const controllers = useRef<Set<AbortController>>(new Set()); |
| 19 | + |
| 20 | + useUnmount(() => { |
| 21 | + for (const controller of controllers.current) { |
| 22 | + controller.abort(); |
| 23 | + } |
| 24 | + controllers.current.clear(); |
| 25 | + }); |
| 26 | + |
| 27 | + return <T = any>(config: AxiosRequestConfig, overrides?: true | HttpRequestConfigOverrides): Promise<T> => { |
| 28 | + const controller = new AbortController(); |
| 29 | + controllers.current.add(controller); |
| 30 | + return axios({ signal: controller.signal, ...config }, overrides) |
| 31 | + .then((res) => res.data) |
| 32 | + .catch((error) => { |
| 33 | + if (error.response) { |
| 34 | + switch (error.response.status) { |
| 35 | + case 401: |
| 36 | + DialogService.open(Toast, { |
| 37 | + children: t('User not authorized'), |
| 38 | + type: 'error', |
| 39 | + }); |
| 40 | + navigate(LOGIN_PATH, { state: { [PREV_ROUTE_KEY]: location } }); |
| 41 | + break; |
| 42 | + |
| 43 | + case 403: |
| 44 | + case 404: |
| 45 | + case 500: |
| 46 | + if (location.pathname !== LOGIN_PATH) { |
| 47 | + navigate(`/exception/${error.response.status}`); |
| 48 | + } |
| 49 | + break; |
| 50 | + |
| 51 | + default: |
| 52 | + break; |
| 53 | + } |
| 54 | + } else if (error.request) { |
| 55 | + // The request was made but no response was received. |
| 56 | + } else { |
| 57 | + // Something happened in setting up the request that triggered an Error. |
| 58 | + } |
| 59 | + }) |
| 60 | + .finally(() => { |
| 61 | + controllers.current.delete(controller); |
| 62 | + }); |
| 63 | + }; |
| 64 | +} |
0 commit comments