From 1d6da48ed6250881aac2e72daebe3f1b08770a85 Mon Sep 17 00:00:00 2001 From: Braden Wong <13159333+braden-w@users.noreply.github.com> Date: Tue, 24 Dec 2024 22:44:12 -0800 Subject: [PATCH] wip feat: runMutation --- src/mutations.ts | 57 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/src/mutations.ts b/src/mutations.ts index 1294cef..bc4e55c 100644 --- a/src/mutations.ts +++ b/src/mutations.ts @@ -4,8 +4,8 @@ import { Ok } from "./result"; export function createMutation< I, O, - MutationFnError, - OnMutateError, + MutationFnError = never, + OnMutateError = never, TContext = undefined, >({ mutationFn, @@ -58,3 +58,56 @@ export function createMutation< }; return mutate; } + +export function runMutation< + O, + MutationFnError = never, + OnMutateError = never, + TContext = undefined, +>({ + mutationFn, + onMutate = () => Ok(undefined as TContext), + onSuccess = () => undefined, + onError = () => undefined, + onSettled = () => undefined, +}: { + mutationFn: (args: { context: TContext }) => + | Promise> + | Result; + onMutate?: () => + | Promise> + | Result; + onSuccess?: (output: O, args: { context: TContext }) => void; + onError?: ( + error: MutationFnError | OnMutateError, + args: { + contextResult: Result; + }, + ) => void; + onSettled?: ( + result: Result, + args: { contextResult: Result }, + ) => void; +}) { + const mutate = async (): Promise => { + const contextResult = await onMutate(); + if (!contextResult.ok) { + const error = contextResult.error; + onError(error, { contextResult }); + onSettled(contextResult, { contextResult }); + return; + } + const context = contextResult.data; + const result = await mutationFn({ context }); + if (!result.ok) { + const error = result.error; + onError(error, { contextResult }); + onSettled(result, { contextResult }); + return; + } + const output = result.data; + onSuccess(output, { context }); + onSettled(result, { contextResult }); + }; + return mutate(); +}