Skip to content

Commit

Permalink
refactor: add OnMutateError generic to createMutation function
Browse files Browse the repository at this point in the history
  • Loading branch information
braden-w committed Dec 25, 2024
1 parent 8e705c7 commit 7f49d16
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/hip-terms-grow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@epicenterhq/result": patch
---

Add OnMutateError generic to createMutation function
25 changes: 18 additions & 7 deletions src/mutations.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import type { Result } from "./result";
import { Ok } from "./result";

export function createMutation<I, O, ServiceError, TContext = undefined>({
export function createMutation<
I,
O,
MutationFnError,
OnMutateError,
TContext = undefined,
>({
mutationFn,
onMutate = () => Ok(undefined as TContext),
onSuccess = () => undefined,
Expand All @@ -11,18 +17,23 @@ export function createMutation<I, O, ServiceError, TContext = undefined>({
mutationFn: (
input: I,
args: { context: TContext },
) => Promise<Result<O, ServiceError>> | Result<O, ServiceError>;
) => Promise<Result<O, MutationFnError>> | Result<O, MutationFnError>;
onMutate?: (
input: I,
) => Promise<Result<TContext, ServiceError>> | Result<TContext, ServiceError>;
) =>
| Promise<Result<TContext, OnMutateError>>
| Result<TContext, OnMutateError>;
onSuccess?: (output: O, args: { input: I; context: TContext }) => void;
onError?: (
error: ServiceError,
args: { input: I; contextResult: Result<TContext, ServiceError> },
error: MutationFnError | OnMutateError,
args: {
input: I;
contextResult: Result<TContext, OnMutateError>;
},
) => void;
onSettled?: (
result: Result<O, ServiceError>,
args: { input: I; contextResult: Result<TContext, ServiceError> },
result: Result<O, MutationFnError | OnMutateError>,
args: { input: I; contextResult: Result<TContext, OnMutateError> },
) => void;
}) {
const mutate = async (input: I): Promise<void> => {
Expand Down
14 changes: 9 additions & 5 deletions src/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@ export type Result<T, E> = { ok: true; data: T } | { ok: false; error: E };
export type Ok<T> = Result<T, never>;
export type Err<E> = Result<never, E>;

export type InferOk<R extends Result<unknown, unknown>> = R extends Ok<infer U>
? U
export type InferOk<R extends Result<unknown, unknown>> = R extends Result<
infer U,
never
>
? Ok<U>
: never;

export type InferErr<R extends Result<unknown, unknown>> = R extends Err<
infer U
export type InferErr<R extends Result<unknown, unknown>> = R extends Result<
never,
infer E
>
? U
? Err<E>
: never;

export const Ok = <T>(data: T): Ok<T> => ({ ok: true, data });
Expand Down

0 comments on commit 7f49d16

Please sign in to comment.