Skip to content

Commit

Permalink
Reimplement map with composables
Browse files Browse the repository at this point in the history
  • Loading branch information
diogob committed May 22, 2024
1 parent 4ad4df2 commit b131daf
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
22 changes: 22 additions & 0 deletions src/constructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,28 @@ import type {
} from './types.ts'
import * as Future from 'npm:composable-functions@beta'

/**
* A functions that helps incremental migration from the legacy `domain-functions` library to the `composable-functions`.
* Both libraries can be installed simultaneously, but to mix and match functions in compositions using `toComposable` and `fromComposable` are necessary to ensure the error types are compatible.
* It will convert any DomainFunction<T> into a Composable<(input?: unknown, environment?: unknown) => T>
*
* @example
* const result = await safeResult(() => ({
* message: 'hello',
* }))
* // the type of result is Result<{ message: string }>
* if (result.success) {
* console.log(result.data.message)
* }
*
* const result = await safeResult(() => {
* throw new Error('something went wrong')
* })
* // the type of result is Result<never>
* if (!result.success) {
* console.log(result.errors[0].message)
* }
*/
function toComposable<R>(
df: DomainFunction<R>,
): Future.Composable<(input?: unknown, environment?: unknown) => R> {
Expand Down
7 changes: 1 addition & 6 deletions src/domain-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,7 @@ function map<O, R>(
dfn: DomainFunction<O>,
mapper: (element: O) => R,
): DomainFunction<R> {
return async (input, environment) => {
const result = await dfn(input, environment)
if (!result.success) return result

return safeResult(() => mapper(result.data))
}
return fromComposable(Future.map(toComposable(dfn), mapper))
}

/**
Expand Down

0 comments on commit b131daf

Please sign in to comment.