mirror of
https://github.com/StanGirard/quivr.git
synced 2024-12-17 23:51:51 +03:00
e29d7483c4
fixed session refresh error # Description Please include a summary of the changes and the related issue. Please also include relevant motivation and context. ## Checklist before requesting a review Please delete options that are not relevant. - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my code - [ ] I have commented hard-to-understand areas - [ ] I have ideally added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] Any dependent changes have been merged ## Screenshots (if appropriate):
51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import axios, {
|
|
AxiosError,
|
|
AxiosInstance,
|
|
InternalAxiosRequestConfig,
|
|
} from "axios";
|
|
|
|
import { useSupabase } from "@/lib/context/SupabaseProvider";
|
|
|
|
import { DEFAULT_BACKEND_URL } from "../config/CONSTANTS";
|
|
|
|
const axiosInstance = axios.create({
|
|
baseURL: `${process.env.NEXT_PUBLIC_BACKEND_URL ?? DEFAULT_BACKEND_URL}`,
|
|
});
|
|
|
|
export const useAxios = (): { axiosInstance: AxiosInstance } => {
|
|
let { session } = useSupabase();
|
|
const { supabase } = useSupabase();
|
|
|
|
axiosInstance.interceptors.request.clear();
|
|
axiosInstance.interceptors.request.use(
|
|
async (value: InternalAxiosRequestConfig) => {
|
|
// Check if the session is valid
|
|
if (
|
|
session &&
|
|
session.expires_at &&
|
|
session.expires_at * 1000 < Date.now()
|
|
) {
|
|
// If the session is not valid, refresh it
|
|
const { data, error } = await supabase.auth.refreshSession();
|
|
if (error) {
|
|
throw error;
|
|
}
|
|
session = data?.session;
|
|
}
|
|
|
|
value.headers = value.headers || {};
|
|
value.headers["Authorization"] = `Bearer ${session?.access_token ?? ""}`;
|
|
|
|
return value;
|
|
},
|
|
(error: AxiosError) => {
|
|
console.error({ error });
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
return {
|
|
axiosInstance,
|
|
};
|
|
};
|