import { useMutation, useQueryClient } from '@tanstack/react-query' import { toast } from 'sonner' import { customDomainKeys } from './keys' import { handleError, post, unguarded } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' import type { UseCustomMutationOptions } from '@/types' export type CustomDomainCreateVariables = { projectRef: string customDomain: string } export async function createCustomDomain({ projectRef, customDomain, }: CustomDomainCreateVariables) { const { data, error } = await post(`/v1/projects/{ref}/custom-hostname/initialize`, { params: { path: { ref: projectRef } }, body: { custom_hostname: customDomain }, grant: unguarded.migrating, }) if (error) handleError(error) return data } type CustomDomainCreateData = Awaited> export const useCustomDomainCreateMutation = ({ onSuccess, onError, ...options }: Omit< UseCustomMutationOptions, 'mutationFn' > = {}) => { const queryClient = useQueryClient() return useMutation({ mutationFn: (vars) => createCustomDomain(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries({ queryKey: customDomainKeys.list(projectRef) }) await onSuccess?.(data, variables, context) }, async onError(data, variables, context) { if (onError === undefined) { toast.error(`Failed to create custom domain: ${data.message}`) } else { onError(data, variables, context) } }, ...options, }) }