Last active
April 5, 2020 20:42
-
-
Save ColemanGariety/c695b5b66efaaae2e2cdfcd3aa38ef59 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
export type FetchSuccess = { response?: Response } & { responseObject?: JsonObject }; | |
export type FetchError = FetchSuccess & { | |
errors: ReadonlyArray<object | string>; | |
} | |
export const post = ( | |
url: string, | |
body: object, | |
) => { | |
const doFetch = TE.tryCatch( | |
async () => ({ | |
response: await fetch(url, { | |
method: 'POST', | |
body: JSON.stringify(body), | |
}), | |
}), | |
error => ({ | |
errors: [error as object], | |
}), | |
); | |
const parse = ( | |
result: FetchSuccess, // error is impossible here | |
): TE.TaskEither<FetchError, FetchSuccess> => | |
((response) => TE.tryCatch( | |
async () => ({ | |
response, | |
responseObject: await response.json(), | |
}), | |
error => ({ | |
response, | |
errors: [error as object], | |
}), | |
))(result.response as Response); | |
const checkOK = (result: FetchError | FetchSuccess) => | |
((response) => pipe(response.ok, fold( | |
() => ({ | |
...result, | |
errors: RA.cons( | |
`Got ${response.status} POSTing to ${url}`, | |
'errors' in result ? result.errors : [], | |
), | |
}), | |
() => result, | |
)))(result.response as Response); | |
return pipe( | |
doFetch, | |
TE.chain(parse), | |
TE.map(checkOK), | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment