Skip to content

Commit

Permalink
Allow mapError to map entire error type (except for its tag) so its a…
Browse files Browse the repository at this point in the history
…nalagous to mapError on DFs
  • Loading branch information
diogob committed Nov 16, 2023
1 parent 5a87169 commit 0ba0b24
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 15 deletions.
10 changes: 5 additions & 5 deletions src/composable/composable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,9 @@ function map<T extends Composable, R>(
) {
return (async (...args) => {
const res = await fn(...args)
if(!res.success) return error(res.errors)
if (!res.success) return error(res.errors)
const mapped = await composable(mapper)(res.data)
if(!mapped.success) return error(mapped.errors)
if (!mapped.success) return error(mapped.errors)
return mapped
}) as Composable<(...args: Parameters<T>) => R>
}
Expand All @@ -135,20 +135,20 @@ function map<T extends Composable, R>(
*/
function mapError<T extends Composable, R>(
fn: T,
mapper: (err: ErrorWithMessage) => ErrorWithMessage,
mapper: (err: Omit<Failure, 'success'>) => Omit<Failure, 'success'>,
) {
return (async (...args) => {
const res = await fn(...args)
return !res.success ? error(res.errors.map(mapper)) : success(res.data)
return !res.success ? error(mapper(res).errors) : success(res.data)
}) as T
}

export {
all,
collect,
composable,
composable as cf,
composable as λ,
collect,
error,
map,
mapError,
Expand Down
15 changes: 5 additions & 10 deletions src/composable/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
assertEquals,
describe,
it,
} from '../test-prelude.ts'
import { assertEquals, describe, it } from '../test-prelude.ts'
import { map, mapError, pipe, sequence } from './index.ts'
import type { Composable, ErrorWithMessage, Result } from './index.ts'
import { Equal, Expect } from './types.test.ts'
Expand Down Expand Up @@ -257,10 +253,7 @@ describe('map', () => {
})

it('maps over a composition', async () => {
const fn = map(
pipe(λ(add), λ(toString)),
(a) => typeof a === 'string',
)
const fn = map(pipe(λ(add), λ(toString)), (a) => typeof a === 'string')
const res = await fn(1, 2)

type _FN = Expect<
Expand Down Expand Up @@ -290,7 +283,9 @@ const cleanError = (err: ErrorWithMessage) => ({
})
describe('mapError', () => {
it('maps over the error results of an Composable function', async () => {
const fn = mapError(λ(faultyAdd), cleanError)
const fn = mapError(λ(faultyAdd), ({ errors }) => ({
errors: errors.map(cleanError),
}))
const res = await fn(1, 2)

type _FN = Expect<
Expand Down

0 comments on commit 0ba0b24

Please sign in to comment.