2023-06-20 17:17:13 +03:00
|
|
|
import axios, { AxiosError, AxiosInstance } from "axios";
|
2023-06-15 12:52:46 +03:00
|
|
|
|
2023-07-05 10:30:22 +03:00
|
|
|
import { useBrainConfig } from "@/lib/context/BrainConfigProvider/hooks/useBrainConfig";
|
|
|
|
import { useSupabase } from "@/lib/context/SupabaseProvider";
|
2023-06-02 18:01:49 +03:00
|
|
|
|
|
|
|
const axiosInstance = axios.create({
|
2023-06-15 12:52:46 +03:00
|
|
|
baseURL: `${process.env.NEXT_PUBLIC_BACKEND_URL ?? ""}`,
|
2023-06-02 18:01:49 +03:00
|
|
|
});
|
|
|
|
|
2023-06-15 12:52:46 +03:00
|
|
|
export const useAxios = (): { axiosInstance: AxiosInstance } => {
|
2023-06-02 18:01:49 +03:00
|
|
|
const { session } = useSupabase();
|
|
|
|
const {
|
2023-06-09 19:49:47 +03:00
|
|
|
config: { backendUrl, openAiKey },
|
2023-06-02 18:01:49 +03:00
|
|
|
} = useBrainConfig();
|
|
|
|
axiosInstance.interceptors.request.clear();
|
|
|
|
axiosInstance.interceptors.request.use(
|
2023-06-15 12:52:46 +03:00
|
|
|
(config) => {
|
2023-06-20 17:17:13 +03:00
|
|
|
config.headers["Authorization"] = `Bearer ${session?.access_token ?? ""}`;
|
2023-06-09 19:49:47 +03:00
|
|
|
config.headers["Openai-Api-Key"] = openAiKey;
|
2023-06-02 18:01:49 +03:00
|
|
|
config.baseURL = backendUrl ?? config.baseURL;
|
|
|
|
|
|
|
|
return config;
|
|
|
|
},
|
2023-06-20 17:17:13 +03:00
|
|
|
(error: AxiosError) => {
|
2023-06-02 18:01:49 +03:00
|
|
|
console.error({ error });
|
|
|
|
void Promise.reject(error);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
axiosInstance,
|
|
|
|
};
|
|
|
|
};
|