Skip to content

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

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

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

export type BranchResetVariables = {
  branchRef: string
  projectRef: string
}

export async function resetBranch({ branchRef }: Pick<BranchResetVariables, 'branchRef'>) {
  const { data, error } = await post('/v1/branches/{branch_id_or_ref}/reset', {
    params: { path: { branch_id_or_ref: branchRef } },
    body: {},
  })

  if (error) handleError(error)
  return data
}

type BranchResetData = Awaited<ReturnType<typeof resetBranch>>

export const useBranchResetMutation = ({
  onSuccess,
  onError,
  ...options
}: Omit<
  UseCustomMutationOptions<BranchResetData, ResponseError, BranchResetVariables>,
  'mutationFn'
> = {}) => {
  const queryClient = useQueryClient()
  return useMutation<BranchResetData, ResponseError, BranchResetVariables>({
    mutationFn: (vars) => resetBranch(vars),
    async onSuccess(data, variables, context) {
      const { projectRef } = variables
      await queryClient.invalidateQueries({ queryKey: branchKeys.list(projectRef) })
      await onSuccess?.(data, variables, context)
    },
    async onError(data, variables, context) {
      if (onError === undefined) {
        toast.error(`Failed to reset branch: ${data.message}`)
      } else {
        onError(data, variables, context)
      }
    },
    ...options,
  })
}