Skip to content

Commit

Permalink
refactor: update first parameter of createMutation for improved clarity
Browse files Browse the repository at this point in the history
  • Loading branch information
braden-w committed Dec 23, 2024
1 parent 0976c8f commit 0cf54d2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 21 deletions.
5 changes: 5 additions & 0 deletions .changeset/cyan-chefs-sniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@epicenterhq/result": patch
---

Update first parameter of createMutation for improved clarity
41 changes: 20 additions & 21 deletions src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,43 +12,42 @@ export function createMutation<I, O, ServiceError, TContext = undefined>({
onError = () => undefined,
onSettled = () => undefined,
}: {
mutationFn: (args: { input: I; context: TContext }) =>
| Promise<Result<O, ServiceError>>
| Result<O, ServiceError>;
mutationFn: (
input: I,
args: { context: TContext },
) => Promise<Result<O, ServiceError>> | Result<O, ServiceError>;
onMutate?: (
input: I,
) => Promise<Result<TContext, ServiceError>> | Result<TContext, ServiceError>;
onSuccess?: (args: { output: O; input: I; context: TContext }) => void;
onError?: (args: {
error: ServiceError;
input: I;
contextResult: Result<TContext, ServiceError>;
}) => void;
onSettled?: (args: {
result: Result<O, ServiceError>;
input: I;
contextResult: Result<TContext, ServiceError>;
}) => void;
onSuccess?: (output: O, args: { input: I; context: TContext }) => void;
onError?: (
error: ServiceError,
args: { input: I; contextResult: Result<TContext, ServiceError> },
) => void;
onSettled?: (
result: Result<O, ServiceError>,
args: { input: I; contextResult: Result<TContext, ServiceError> },
) => void;
}) {
const mutate = async (input: I): Promise<void> => {
const contextResult = await onMutate(input);
if (!contextResult.ok) {
const error = contextResult.error;
onError({ error, input, contextResult });
onSettled({ result: contextResult, input, contextResult });
onError(error, { input, contextResult });
onSettled(contextResult, { input, contextResult });
return;
}
const context = contextResult.data;
const result = await mutationFn({ input, context });
const result = await mutationFn(input, { context });
if (!result.ok) {
const error = result.error;
onError({ error, input, contextResult });
onSettled({ result, input, contextResult });
onError(error, { input, contextResult });
onSettled(result, { input, contextResult });
return;
}
const output = result.data;
onSuccess({ output, input, context });
onSettled({ result, input, contextResult });
onSuccess(output, { input, context });
onSettled(result, { input, contextResult });
};
return { mutate };
}

0 comments on commit 0cf54d2

Please sign in to comment.