MIF_E31221222/sigap-website/app/_hooks/use-supabase.ts

75 lines
1.8 KiB
TypeScript

/**
* Custom hook to interact with Supabase client.
*
* @returns {Object} An object containing the Supabase client and session management functions.
*
* @function
* @name useSupabase
*
* @example
* const { supabase, getSession, refreshSession, setSession } = useSupabase();
*
* @property {Object} supabase - The Supabase client instance.
* @property {Function} getSession - Function to get the current session.
* @property {Function} refreshSession - Function to refresh the current session.
* @property {Function} setSession - Function to set a new session with access and refresh tokens.
*
* @typedef {Object} Session
* @property {string} access_token - The access token for the session.
* @property {string} refresh_token - The refresh token for the session.
*
* @throws {Error} Throws an error if there is an issue with getting or setting the session.
*/
//
import { createClient } from "@/utils/supabase/client";
export const useSupabase = () => {
const supabase = createClient();
const getSession = async () => {
const {
data: { session },
error,
} = await supabase.auth.getSession();
if (error) {
throw new Error(error.message);
}
const { access_token, refresh_token }: any = session;
await setSession(access_token, refresh_token);
return session;
};
const refreshSession = async () => {
const {
data: { session },
error,
} = await supabase.auth.refreshSession();
return session;
};
const setSession = async (access_token: string, refresh_token: string) => {
const { data, error } = await supabase.auth.setSession({
access_token,
refresh_token,
});
if (error) {
throw new Error(error.message);
}
return true;
};
return {
getSession,
refreshSession,
setSession,
};
};