Skip to content

Instantly share code, notes, and snippets.

@samrocksc
Created April 10, 2022 16:42
Show Gist options
  • Save samrocksc/5294beea17ab2ed1bfed846dd7971c60 to your computer and use it in GitHub Desktop.
Save samrocksc/5294beea17ab2ed1bfed846dd7971c60 to your computer and use it in GitHub Desktop.
Functional isometric-fetch
import fetch from 'isomorphic-unfetch';
import { pipe } from 'fp-ts/lib/function';
import * as TE from 'fp-ts/lib/TaskEither';
import * as E from 'fp-ts/lib/Either';
import * as O from 'fp-ts/lib/Option';
export const url = 'https://swapi.dev/api/planets/1/';
export const log = <A>(x: A) => {
console.info(x);
return x;
};
export type ThingWithAName = {
readonly name: string;
readonly rotation_period: string;
};
export const safeJson = <T = unknown>(
resp: Response
): TE.TaskEither<Error, T> =>
TE.tryCatch(
() => resp.json(),
(reason) => new Error(String(reason))
);
(async () => {
const initialFetch = pipe(
TE.tryCatch(
() => fetch(url),
() => O.none
),
TE.chain((resp) =>
TE.tryCatch(
(): Promise<ThingWithAName> => resp.json(),
() => O.some('Failed to read json from response')
)
)
);
const data = pipe(
await initialFetch(),
E.getOrElseW(() => Error('Data Failed'))
);
console.log(data);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment