Skip to content

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

2.2 KB
Raw Blame
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { components } from 'api-types'
import { toast } from 'sonner'

import { storageKeys } from './keys'
import { handleError, post } from '@/data/fetchers'
import type { ResponseError, UseCustomMutationOptions } from '@/types'

type BucketCreateVariables = Omit<CreateStorageBucketBody, 'public'> & {
  projectRef: string
  isPublic: boolean
}

type CreateStorageBucketBody = components['schemas']['CreateStorageBucketBody']

async function createBucket({
  projectRef,
  id,
  type,
  isPublic,
  file_size_limit,
  allowed_mime_types,
  versioning_status,
}: BucketCreateVariables) {
  if (!projectRef) throw new Error('projectRef is required')
  if (!id) throw new Error('Bucket name is required')

  const payload: CreateStorageBucketBody = { id, type, public: isPublic }
  if (type === 'STANDARD') {
    if (file_size_limit) payload.file_size_limit = file_size_limit
    if (allowed_mime_types) payload.allowed_mime_types = allowed_mime_types
    if (versioning_status) payload.versioning_status = versioning_status
  }

  const { data, error } = await post('/platform/storage/{ref}/buckets', {
    params: { path: { ref: projectRef } },
    body: payload,
  })

  if (error) handleError(error)
  return data as { name: string }
}

type BucketCreateData = Awaited<ReturnType<typeof createBucket>>

export const useBucketCreateMutation = ({
  onSuccess,
  onError,
  ...options
}: Omit<
  UseCustomMutationOptions<BucketCreateData, ResponseError, BucketCreateVariables>,
  'mutationFn'
> = {}) => {
  const queryClient = useQueryClient()

  return useMutation<BucketCreateData, ResponseError, BucketCreateVariables>({
    mutationFn: (vars) => createBucket(vars),
    async onSuccess(data, variables, context) {
      const { projectRef } = variables
      await queryClient.invalidateQueries({ queryKey: storageKeys.buckets(projectRef) })
      await onSuccess?.(data, variables, context)
    },
    async onError(data, variables, context) {
      if (onError === undefined) {
        toast.error(`Failed to create bucket: ${data.message}`)
      } else {
        onError(data, variables, context)
      }
    },
    ...options,
  })
}