Skip to content

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

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

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

export type AWSAccountCreateVariables = {
  projectRef: string
  awsAccountId: string
  accountName?: string
  databaseIdentifier?: string
}

export async function createAWSAccount({
  projectRef,
  awsAccountId,
  accountName,
  databaseIdentifier,
}: AWSAccountCreateVariables) {
  const { data, error } = await post(
    '/platform/projects/{ref}/privatelink/associations/aws-account',
    {
      params: {
        path: { ref: projectRef },
      },
      body: {
        aws_account_id: awsAccountId,
        account_name: accountName,
        database_identifier: databaseIdentifier,
      },
    }
  )

  if (error) handleError(error)
  return data
}

type AWSAccountCreateData = Awaited<ReturnType<typeof createAWSAccount>>

export const useAWSAccountCreateMutation = ({
  onSuccess,
  onError,
  ...options
}: Omit<
  UseMutationOptions<AWSAccountCreateData, ResponseError, AWSAccountCreateVariables>,
  'mutationFn'
> = {}) => {
  const queryClient = useQueryClient()
  return useMutation<AWSAccountCreateData, ResponseError, AWSAccountCreateVariables>({
    mutationFn: (vars) => createAWSAccount(vars),
    async onSuccess(data, variables, context, mutationContext) {
      const { projectRef } = variables
      await queryClient.invalidateQueries({ queryKey: awsAccountKeys.list(projectRef) })
      await onSuccess?.(data, variables, context, mutationContext)
    },
    async onError(data, variables, context, mutationContext) {
      if (onError === undefined) {
        toast.error(`Failed to create connection: ${data.message}`)
      } else {
        onError(data, variables, context, mutationContext)
      }
    },
    ...options,
  })
}