import { useQuery, UseQueryOptions } from '@tanstack/react-query' import { get, handleError } from 'data/fetchers' import { useSelectedProject } from 'hooks/misc/useSelectedProject' import { PROJECT_STATUS } from 'lib/constants' import type { ResponseError } from 'types' import { storageKeys } from './keys' export type BucketsVariables = { projectRef?: string } export type Bucket = { id: string name: string owner: string public: boolean created_at: string updated_at: string file_size_limit: null | number allowed_mime_types: null | string[] } export async function getBuckets({ projectRef }: BucketsVariables, signal?: AbortSignal) { if (!projectRef) throw new Error('projectRef is required') const { data, error } = await get('/platform/storage/{ref}/buckets', { params: { path: { ref: projectRef } }, signal, }) if (error) handleError(error) return data as Bucket[] } export type BucketsData = Awaited> export type BucketsError = ResponseError export const useBucketsQuery = ( { projectRef }: BucketsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => { const project = useSelectedProject() const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY return useQuery( storageKeys.buckets(projectRef), ({ signal }) => getBuckets({ projectRef }, signal), { enabled: enabled && typeof projectRef !== 'undefined' && isActive, ...options, retry: (failureCount, error) => { if ( typeof error === 'object' && error !== null && error.message.startsWith('Tenant config') && error.message.endsWith('not found') ) { return false } if (failureCount < 3) { return true } return false }, } ) }