Skip to content

Commit

Permalink
Enable catcher with different types
Browse files Browse the repository at this point in the history
  • Loading branch information
diogob committed Apr 5, 2024
1 parent 13af7c3 commit 0840288
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
10 changes: 5 additions & 5 deletions src/composable/composable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,18 +198,18 @@ function map<T extends Composable, R>(
* originalInput.id * -1
* ))
*/
function catchError<T extends Composable, R>(
fn: T,
function catchError<T extends Fn, R>(
fn: Composable<T>,
catcher: (
err: Omit<Failure, 'success'>,
...originalInput: Parameters<T>
) => UnpackResult<ReturnType<T>>,
) => R,
) {
return (async (...args) => {
return (async (...args: Parameters<T>) => {
const res = await fn(...args)
if (res.success) return success(res.data)
return composable(catcher)(res, ...(args as any))
}) as T
}) as Composable<(...args: Parameters<T>) => ReturnType<T> | R>
}

/**
Expand Down
18 changes: 17 additions & 1 deletion src/composable/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,23 @@ describe('mapError', () => {
})

describe('catchError', () => {
it('receives an error as input to another composable', async () => {
it('changes the type to accomodate catcher return type', async () => {
const fn = catchError(faultyAdd, () => null)
const res = await fn(1, 2)

type _FN = Expect<
Equal<typeof fn, Composable<(a: number, b: number) => number | null>>
>
type _R = Expect<Equal<typeof res, Result<number | null>>>

assertEquals(res, {
success: true,
data: null,
errors: [],
})
})

it('receives an error as input to another function and returns a new composable', async () => {
const fn = catchError(faultyAdd, (_error, a, b) => a + b)
const res = await fn(1, 2)

Expand Down

0 comments on commit 0840288

Please sign in to comment.