Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

1.6 KB
Raw Blame
import { useMutation } from '@tanstack/react-query'
import { toast } from 'sonner'

import { del, handleError } from '@/data/fetchers'
import type { ResponseError, UseCustomMutationOptions } from '@/types'

type DeleteBucketObjectParams = {
  projectRef: string
  bucketId?: string
  paths: string[]
}
export const deleteBucketObject = async (
  { projectRef, bucketId, paths }: DeleteBucketObjectParams,
  signal?: AbortSignal
) => {
  if (!bucketId) throw new Error('bucketId is required')

  const { data, error } = await del('/platform/storage/{ref}/buckets/{id}/objects', {
    params: {
      path: {
        ref: projectRef,
        id: bucketId,
      },
    },
    body: {
      paths,
    },
    signal,
  })

  if (error) handleError(error)
  return data
}

type BucketObjectDeleteData = Awaited<ReturnType<typeof deleteBucketObject>>

export const useBucketObjectDeleteMutation = ({
  onSuccess,
  onError,
  ...options
}: Omit<
  UseCustomMutationOptions<BucketObjectDeleteData, ResponseError, DeleteBucketObjectParams>,
  'mutationFn'
> = {}) => {
  return useMutation<BucketObjectDeleteData, ResponseError, DeleteBucketObjectParams>({
    mutationFn: (vars) => deleteBucketObject(vars),
    async onSuccess(data, variables, context) {
      // [Joshen] TODO figure out what queries to invalidate
      await onSuccess?.(data, variables, context)
    },
    async onError(data, variables, context) {
      if (onError === undefined) {
        toast.error(`Failed to delete bucket object: ${data.message}`)
      } else {
        onError(data, variables, context)
      }
    },
    ...options,
  })
}