Skip to content

Instantly share code, notes, and snippets.

@AlexGeb
Last active November 22, 2023 13:33
Show Gist options
  • Save AlexGeb/c2b51410401dca7689a8faebdfb1c94e to your computer and use it in GitHub Desktop.
Save AlexGeb/c2b51410401dca7689a8faebdfb1c94e to your computer and use it in GitHub Desktop.
fp-ts to effect conversions
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>;
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