Created
February 20, 2022 22:10
-
-
Save hungneox/b6d01686a90965164193651a77f1cd14 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 axios, { AxiosResponse } from "axios"; | |
import * as F from "fp-ts/function"; | |
import * as E from "fp-ts/Either"; | |
import * as T from "fp-ts/Task"; | |
import * as TE from "fp-ts/TaskEither"; | |
type ToDo = { | |
userId: number; | |
id: number; | |
title: string; | |
completed: boolean; | |
}; | |
const safeGet = (url: string): TE.TaskEither<Error, AxiosResponse> => | |
TE.tryCatch(() => axios.get(url), E.toError); | |
const fetchTodo = (id: number): TE.TaskEither<string, ToDo> => | |
F.pipe( | |
safeGet(`https://jsonplaceholder.typicode.com/todos/${id}`), | |
TE.fold( | |
(e: Error) => T.of(e.message), | |
(a: AxiosResponse) => T.of(a.data) | |
) | |
); | |
const main = async () => { | |
const resp = await fetchTodo(1)(); | |
// { userId: 1, id: 1, title: 'delectus aut autem', completed: false } | |
console.log(resp); | |
const resp1 = await fetchTodo(3)(); | |
// { userId: 1, id: 3, title: 'fugiat veniam minus', completed: false } | |
console.log(resp1); | |
const resp2 = await fetchTodo(0)(); | |
// Request failed with status code 404 | |
console.log(resp2); | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment