Skip to content

Commit

Permalink
wip feat: runMutation
Browse files Browse the repository at this point in the history
  • Loading branch information
braden-w committed Dec 25, 2024
1 parent 7f49d16 commit 1d6da48
Showing 1 changed file with 55 additions and 2 deletions.
57 changes: 55 additions & 2 deletions src/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { Ok } from "./result";
export function createMutation<
I,
O,
MutationFnError,
OnMutateError,
MutationFnError = never,
OnMutateError = never,
TContext = undefined,
>({
mutationFn,
Expand Down Expand Up @@ -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<O, MutationFnError>>
| Result<O, MutationFnError>;
onMutate?: () =>
| Promise<Result<TContext, OnMutateError>>
| Result<TContext, OnMutateError>;
onSuccess?: (output: O, args: { context: TContext }) => void;
onError?: (
error: MutationFnError | OnMutateError,
args: {
contextResult: Result<TContext, OnMutateError>;
},
) => void;
onSettled?: (
result: Result<O, MutationFnError | OnMutateError>,
args: { contextResult: Result<TContext, OnMutateError> },
) => void;
}) {
const mutate = async (): Promise<void> => {
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();
}

0 comments on commit 1d6da48

Please sign in to comment.