Skip to content

Instantly share code, notes, and snippets.

@rawnly
Last active May 6, 2022 22:05
Show Gist options
  • Save rawnly/a5a1bcf81208df42ba971c4a23f4b986 to your computer and use it in GitHub Desktop.
Save rawnly/a5a1bcf81208df42ba971c4a23f4b986 to your computer and use it in GitHub Desktop.
import * as RD from '@devexperts/remote-data-ts';
import * as E from 'fp-ts/Either';
import { flow, Lazy, pipe } from 'fp-ts/lib/function';
import * as T from 'fp-ts/Task';
import * as TE from 'fp-ts/TaskEither';
import Task = T.Task;
import Either = E.Either;
import TaskEither = TE.TaskEither;
import RemoteData = RD.RemoteData;
export interface TaskRemoteData<E, T> extends Task<RemoteData<E, T>> {}
export const tryCatch =
<E, T>(promise: Lazy<Promise<T>>, onError: (response: unknown) => E): TaskRemoteData<E, T> =>
async () => {
try {
return await promise().then(RD.success);
} catch (error) {
return RD.failure(onError(error));
}
};
export const map =
<A, B>(f: (a: A) => B) =>
<E>(fa: TaskRemoteData<E, A>): TaskRemoteData<E, B> =>
pipe(fa, T.map(RD.map(f)));
export const mapLeft =
<E, G>(f: (e: E) => G) =>
<A>(fa: TaskRemoteData<E, A>): TaskRemoteData<G, A> =>
pipe(fa, T.map(RD.mapLeft(f)));
export const success = <A>(a: A) => T.of(RD.success(a));
export const failure = <E>(e: E) => T.of(RD.failure(e));
// export const chain =
// <E, A, B>(f: (a: A) => RD.RemoteData<E, B>) =>
// (ma: TaskRemoteData<E, A>): TaskRemoteData<E, B> =>
// pipe(ma, T.chain(flow(RD.chain(f), T.of)));
type Mapper<A, B> = (a: A) => B;
export const chainRemoteData =
<E, A, B>(f: Mapper<A, RemoteData<E, B>>) =>
(ma: TaskRemoteData<E, A>): TaskRemoteData<E, B> =>
pipe(ma, T.chain(flow(RD.chain<E, A, B>(f), T.of)));
export const chainEitherK =
<E, A, B>(f: Mapper<A, Either<E, B>>) =>
(ma: TaskRemoteData<E, A>): TaskRemoteData<E, B> =>
pipe(ma, T.chain(flow(RD.chain<E, A, B>(flow(f, RD.fromEither)), T.of)));
export const chainEitherKW: <E2, A, B>(f: Mapper<A, Either<E2, B>>) => <E1>(ma: TaskRemoteData<E1, A>) => TaskRemoteData<E1 | E2, B> = chainEitherK as any;
export const fromTaskEither: <E, A>(te: TaskEither<E, A>) => TaskRemoteData<E, A> = T.map(RD.fromEither);
export const fromEither: <E, A>(te: Either<E, A>) => TaskRemoteData<E, A> = flow(RD.fromEither, T.of);
export const fromRemoteData: <E, A>(rd: RemoteData<E, A>) => TaskRemoteData<E, A> = T.of;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment