import { shallowRef, type ShallowRef } from 'vue' import type { MutationDef, QueryStatus } from '../core/types' import { Status } from '../core/flags' import { useEngine } from './useEngine' export interface UseMutationReturn { mutate: (input: TInput) => void mutateAsync: (input: TInput) => Promise status: ShallowRef error: ShallowRef data: ShallowRef } export function useMutation( def: MutationDef, ): UseMutationReturn { const engine = useEngine() const status = shallowRef(Status.Idle) const error = shallowRef(undefined) const data = shallowRef(undefined) async function mutateAsync(input: TInput): Promise { status.value = Status.Pending error.value = undefined try { const resp = (await engine.mutate(def.name, input)) as TResp data.value = resp status.value = Status.Success return resp } catch (e) { error.value = e as Error status.value = Status.Error throw e } } function mutate(input: TInput): void { void mutateAsync(input).catch(() => {}) } return { mutate, mutateAsync, status, error, data } }