UNPKG

@daveyplate/supabase-swr-entities

Version:

An entity management library for Supabase and SWR

33 lines (32 loc) 1.61 kB
import { useSession } from "@supabase/auth-helpers-react"; import { useCallback } from "react"; import { isExport } from "./client-utils"; export function useAPI() { const session = useSession(); const requestAPI = useCallback(async (path, method, body) => { var _a; const baseUrl = isExport() ? process.env.NEXT_PUBLIC_BASE_URL : ""; const url = baseUrl + path; const res = await fetch(url, { method, headers: (isExport() && session) ? { 'Authorization': `Bearer ${session.access_token}`, 'Content-Type': 'application/json' } : { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); if (!res.ok) { // Attach extra info to the error object. const json = await res.json(); const error = new Error(((_a = json === null || json === void 0 ? void 0 : json.error) === null || _a === void 0 ? void 0 : _a.message) || `Failed to fetch ${path}`); console.error(error); throw error; } return res.json(); }, [session]); const getAPI = useCallback(async (path) => requestAPI(path, 'GET'), [requestAPI]); const postAPI = useCallback(async (path, body) => requestAPI(path, 'POST', body), [requestAPI]); const patchAPI = useCallback(async (path, body) => requestAPI(path, 'PATCH', body), [requestAPI]); const deleteAPI = useCallback(async (path) => requestAPI(path, 'DELETE'), [requestAPI]); return { getAPI, postAPI, patchAPI, deleteAPI, requestAPI }; }