import { useMutation, useQueryClient } from '@tanstack/react-query' import { toast } from 'sonner' import { networkRestrictionKeys } from './keys' import { configKeys } from '@/data/config/keys' import { handleError, post, unguarded } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' import type { UseCustomMutationOptions } from '@/types' export type NetworkRestrictionsApplyVariables = { projectRef: string dbAllowedCidrs: string[] dbAllowedCidrsV6: string[] } export async function applyNetworkRestrictions({ projectRef, dbAllowedCidrs, dbAllowedCidrsV6, }: NetworkRestrictionsApplyVariables) { if (!projectRef) throw new Error('projectRef is required') const { data, error } = await post('/v1/projects/{ref}/network-restrictions/apply', { params: { path: { ref: projectRef } }, body: { dbAllowedCidrs, dbAllowedCidrsV6 }, grant: unguarded.migrating, }) if (error) handleError(error) return data } type NetworkRestrictionsApplyData = Awaited> export const useNetworkRestrictionsApplyMutation = ({ onSuccess, onError, ...options }: Omit< UseCustomMutationOptions< NetworkRestrictionsApplyData, StudioError, NetworkRestrictionsApplyVariables >, 'mutationFn' > = {}) => { const queryClient = useQueryClient() return useMutation({ mutationFn: (vars) => applyNetworkRestrictions(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await Promise.all([ queryClient.invalidateQueries({ queryKey: networkRestrictionKeys.list(projectRef) }), queryClient.invalidateQueries({ queryKey: configKeys.projectConfig(projectRef) }), ]) await onSuccess?.(data, variables, context) }, async onError(data, variables, context) { if (onError === undefined) { toast.error(`Failed to apply network restrictions: ${data.message}`) } else { onError(data, variables, context) } }, ...options, }) }