import { useQuery, useQueryClient } from '@tanstack/react-query' import { useCallback } from 'react' import { resourceKeys } from './keys' import { get, handleError } from '@/data/fetchers' import type { ResponseError, UseCustomQueryOptions } from '@/types' export type ResourceVariables = { projectRef?: string id?: string } export type ResourceResponse = { id: string } export async function getResource({ projectRef, id }: ResourceVariables, signal?: AbortSignal) { if (!projectRef) throw new Error('projectRef is required') // @ts-ignore Just a sample here, TS lint will validate if the endpoint is valid const { data, error } = await get(`/platform/projects/{ref}/resources/{id}`, { params: { path: { ref: projectRef, id } }, signal, }) if (error) handleError(error) return data } export type ResourceData = Awaited> export type ResourceError = ResponseError export const useResourceQuery = ( { projectRef, id }: ResourceVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => useQuery({ queryKey: resourceKeys.resource(projectRef, id), queryFn: ({ signal }) => getResource({ projectRef, id }, signal), enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', ...options, }) /** * useResourcePrefetch is used for prefetching data. For example, starting a query loading before a page is navigated to. * Feel free to omit if not required * * @example * const prefetch = useResourcePrefetch({ projectRef, id }) * * return ( * prefetch()}> * Start loading on hover * * ) */ export const useResourcePrefetch = ({ projectRef, id }: ResourceVariables) => { const client = useQueryClient() return useCallback(() => { if (projectRef && id) { client.prefetchQuery({ queryKey: resourceKeys.resource(projectRef, id), queryFn: ({ signal }) => getResource({ projectRef, id }, signal), }) } }, [projectRef, id]) }