import type { TypedDocumentNode } from '@apollo/client' import type { useMutation } from '@apollo/client/react' import { useMutation as useMutationHook } from '@apollo/client/react' import type { FieldValues, UseFormReturn } from 'react-hook-form' import { useForm } from 'react-hook-form' import type { UseFormGqlMethods, UseFormGraphQlOptions } from './useFormGql' import { useFormGql, UseFormGqlSymbol } from './useFormGql' export type UseFormGqlMutationReturn< // eslint-disable-next-line @typescript-eslint/no-explicit-any Q extends Record = Record, V extends FieldValues = FieldValues, > = Omit, 'handleSubmit'> & UseFormGqlMethods export function isFormGqlOperation< V extends FieldValues, Q extends Record = Record, // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-redundant-type-constituents >(form: any): form is UseFormGqlMutationReturn { return (form as UseFormGqlMutationReturn)[UseFormGqlSymbol] === true } export function assertFormGqlOperation< V extends FieldValues, Q extends Record = Record, >(form: UseFormReturn): asserts form is UseFormGqlMutationReturn { if (!isFormGqlOperation(form)) throw Error("form must be one of 'useFromGqlMutation' or 'useFormGqlQuery'") } /** Bindings between react-hook-form's useForm and Apollo Client's useMutation hook. */ export function useFormGqlMutation, V extends FieldValues>( document: TypedDocumentNode, options: NoInfer> = {}, operationOptions?: useMutation.Options, NoInfer>, ): UseFormGqlMutationReturn { const form = useForm(options) const tuple = useMutationHook(document, operationOptions as useMutation.Options) const operation = useFormGql({ document, form, tuple, operationOptions, ...options }) // operation.handleSubmit overrides form.handleSubmit return { ...form, ...operation } as unknown as UseFormGqlMutationReturn }