import { Either , Left , Right } from "fp-ts/lib/Either" ; import { Type , Errors } from "io-ts" ; import { reporter } from "io-ts-reporters" ; export async function fetchJson < T , O , I > ( url , validator , init ? ) { try { const response = await fetch ( url , init ) ; const json = await response . json ( ) ; const result = validator . decode ( json ) ; return result . fold < Either < Error , T > > ( ( errors ) => { const messages = reporter ( result ) ; return new Left < Error , T > ( new Error ( messages . join ( "\n" ) ) ) ; } , ( value ) => { return new Right < Error , T > ( value ) ; } ) ; } catch ( err ) { return Promise . resolve ( new Left < Error , T > ( err ) ) ; } }