import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query' import { toast } from 'sonner' import { jitDbAccessKeys } from './keys' import { handleError, put, unguarded } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' type JitDbAccessGrantVariables = { projectRef: string userId: string roles: Array<{ role: string branches_only?: boolean expires_at?: number // Unix timestamp in seconds per role allowed_networks?: { allowed_cidrs?: Array<{ cidr: string }> allowed_cidrs_v6?: Array<{ cidr: string }> } }> } async function grantJitDbAccess({ projectRef, userId, roles }: JitDbAccessGrantVariables) { if (!projectRef) throw new Error('projectRef is required') if (!userId) throw new Error('userId is required') if (!roles || roles.length === 0) throw new Error('At least one role is required') const { data, error } = await put(`/v1/projects/{ref}/database/jit`, { params: { path: { ref: projectRef } }, body: { user_id: userId, roles, }, grant: unguarded.migrating, }) if (error) handleError(error) return data } type JitDbAccessGrantData = Awaited> export const useJitDbAccessGrantMutation = ({ onSuccess, onError, ...options }: Omit< UseMutationOptions, 'mutationFn' > = {}) => { const queryClient = useQueryClient() return useMutation({ mutationFn: (vars) => grantJitDbAccess(vars), async onSuccess(data, variables, context, mutationContext) { const { projectRef } = variables await Promise.all([ queryClient.invalidateQueries({ queryKey: jitDbAccessKeys.members(projectRef) }), queryClient.invalidateQueries({ queryKey: jitDbAccessKeys.status(projectRef) }), ]) await onSuccess?.(data, variables, context, mutationContext) }, async onError(data, variables, context, mutationContext) { if (onError === undefined) { toast.error(`Failed to save member access rule: ${data.message}`) } else { onError(data, variables, context, mutationContext) } }, ...options, }) }