Last active
November 22, 2023 13:33
-
-
Save AlexGeb/c2b51410401dca7689a8faebdfb1c94e to your computer and use it in GitHub Desktop.
fp-ts to effect conversions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Context, Effect, pipe } from 'effect'; | |
import { either } from 'fp-ts'; | |
import { ReaderTaskEither } from 'fp-ts/ReaderTaskEither'; | |
import { TaskEither } from 'fp-ts/TaskEither'; | |
export const effectFromEither = either.matchW(Effect.fail, Effect.succeed); | |
export const effectFromTaskEither = <E, A>( | |
program: TaskEither<E, A>, | |
): Effect.Effect<never, E, A> => | |
pipe(Effect.promise(program), Effect.flatMap(effectFromEither)); | |
export const effectFromReaderTaskEither = | |
<P extends Array<any>, R extends Record<string, any>, M extends R, E, A>( | |
program: (...props: P) => ReaderTaskEither<M, E, A>, | |
dependencies: { [Key in keyof R]: Context.Tag<R[Key], R[Key]> }, | |
) => | |
(...props: P) => | |
pipe( | |
Effect.all(dependencies as Record<string, any>), | |
Effect.flatMap(deps => | |
effectFromTaskEither(program(...props)(deps as M)), | |
), | |
) as Effect.Effect<R[keyof R], E, A>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Context, pipe } from 'effect'; | |
import { reader } from 'fp-ts'; | |
import { TaskEither } from 'fp-ts/TaskEither'; | |
import { effectFromReaderTaskEither } from './effectFromFpTs'; | |
type Service = { | |
doSomething: (arg: string) => TaskEither<'error', string>; | |
}; | |
const fpTsProgram = (arg: string) => | |
pipe( | |
reader.ask<{ service: Service }>(), | |
reader.map(({ service }) => service.doSomething(arg)), | |
); | |
const Service = Context.Tag<Service>(); | |
const effectProgram = effectFromReaderTaskEither(fpTsProgram, { | |
service: Service, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment