2023-12-08 14:33:22 +01:00
|
|
|
import { baseUrl } from "./baseUrl";
|
2024-02-27 17:05:28 +01:00
|
|
|
import { SWRConfig } from "swr";
|
2023-12-08 14:33:22 +01:00
|
|
|
import { WsProvider } from "./ws";
|
|
|
|
import axios from "axios";
|
|
|
|
import { ReactNode } from "react";
|
|
|
|
|
|
|
|
axios.defaults.baseURL = `${baseUrl}api/`;
|
|
|
|
|
|
|
|
type ApiProviderType = {
|
|
|
|
children?: ReactNode;
|
|
|
|
options?: Record<string, unknown>;
|
|
|
|
};
|
|
|
|
|
|
|
|
export function ApiProvider({ children, options }: ApiProviderType) {
|
|
|
|
axios.defaults.headers.common = {
|
|
|
|
"X-CSRF-TOKEN": 1,
|
|
|
|
"X-CACHE-BYPASS": 1,
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<SWRConfig
|
|
|
|
value={{
|
|
|
|
fetcher: (key) => {
|
|
|
|
const [path, params] = Array.isArray(key) ? key : [key, undefined];
|
|
|
|
return axios.get(path, { params }).then((res) => res.data);
|
|
|
|
},
|
2024-05-18 18:36:13 +02:00
|
|
|
onError: (error, _key) => {
|
|
|
|
if ([401, 302, 307].includes(error.response.status)) {
|
|
|
|
window.location.href =
|
|
|
|
error.response.headers.get("location") ?? "login";
|
|
|
|
}
|
|
|
|
},
|
2023-12-08 14:33:22 +01:00
|
|
|
...options,
|
|
|
|
}}
|
|
|
|
>
|
|
|
|
<WsWithConfig>{children}</WsWithConfig>
|
|
|
|
</SWRConfig>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
type WsWithConfigType = {
|
|
|
|
children: ReactNode;
|
|
|
|
};
|
|
|
|
|
|
|
|
function WsWithConfig({ children }: WsWithConfigType) {
|
2024-02-27 17:05:28 +01:00
|
|
|
return <WsProvider>{children}</WsProvider>;
|
2023-12-08 14:33:22 +01:00
|
|
|
}
|
|
|
|
|
2024-05-18 18:36:13 +02:00
|
|
|
// eslint-disable-next-line react-refresh/only-export-components
|
2023-12-08 14:33:22 +01:00
|
|
|
export function useApiHost() {
|
|
|
|
return baseUrl;
|
|
|
|
}
|