import { useMutation } from '@tanstack/react-query' import { toast } from 'sonner' import { components } from '@/data/api' import { handleError, post } from '@/data/fetchers' import type { ResponseError, UseCustomMutationOptions } from '@/types' type ListBucketObjectsParams = { projectRef: string bucketId?: string path: string options: components['schemas']['GetObjectsBody']['options'] } export type StorageObject = components['schemas']['StorageObject_Output'] // [Joshen] Ideally we transform this into a query that uses a POST i think export const listBucketObjects = async ( { projectRef, bucketId, path, options }: ListBucketObjectsParams, signal?: AbortSignal ) => { if (!bucketId) throw new Error('bucketId is required') const { data, error } = await post('/platform/storage/{ref}/buckets/{id}/objects/list', { params: { path: { ref: projectRef, id: bucketId, }, }, body: { path, options, }, signal, }) if (error) handleError(error) return data } type ListBucketObjectsData = Awaited> type ListBucketObjectsV2Params = { projectRef: string bucketId?: string prefix: string cursor?: string options?: Omit } export const listBucketObjectsV2 = async ( { projectRef, bucketId, prefix, cursor, options }: ListBucketObjectsV2Params, signal?: AbortSignal ) => { if (!bucketId) throw new Error('bucketId is required') const { data, error } = await post('/platform/storage/{ref}/buckets/{id}/objects/list-v2', { params: { path: { ref: projectRef, id: bucketId, }, }, body: { prefix, cursor, with_delimiter: true, ...options, }, signal, }) if (error) handleError(error) return data } export const useGetSignBucketObjectMutation = ({ onSuccess, onError, ...options }: Omit< UseCustomMutationOptions, 'mutationFn' > = {}) => { return useMutation({ mutationFn: (vars) => listBucketObjects(vars), async onSuccess(data, variables, context) { await onSuccess?.(data, variables, context) }, async onError(data, variables, context) { if (onError === undefined) { toast.error(`Failed to list bucket objects: ${data.message}`) } else { onError(data, variables, context) } }, ...options, }) }