Last active
May 6, 2022 22:05
-
-
Save rawnly/a5a1bcf81208df42ba971c4a23f4b986 to your computer and use it in GitHub Desktop.
This file contains 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 * 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