입력:23/01/25수정:24/01/05
예시) 원격 restful 요청 + 에러핸들링
// 데이터를 요청하는 부분
const httpGet = (url:string) => TE.tryCatch<Error, AxiosResponse>(
() => axios.get(url),
reason => new Error(String(reason))
)
//요청한 데이터를 decode 하는 코드
const getUser = pipe(
httpGet('https://reqres.in/api/users?page=1'),
TE.map(x => x.data),
TE.chain((str) => pipe(
users.decode(str),
E.mapLeft(err => new Error(String(err))),
TE.fromEither)
)
);
import { pipe } from "fp-ts/lib/pipeable";
import * as E from "fp-ts/lib/Either";
import * as TE from "fp-ts/lib/TaskEither";
function getStuff(u: string): TE.TaskEither<Error, unknown> {
return TE.tryCatch(
() =>
fetch(u).then(res => {
if (!res.ok) {
throw new Error(`fetch failed with status: ${res.status}`);
}
return res.json();
}),
E.toError
);
}