Skip to content

Instantly share code, notes, and snippets.

@ColemanGariety
Last active April 5, 2020 20:42
Show Gist options
  • Save ColemanGariety/c695b5b66efaaae2e2cdfcd3aa38ef59 to your computer and use it in GitHub Desktop.
Save ColemanGariety/c695b5b66efaaae2e2cdfcd3aa38ef59 to your computer and use it in GitHub Desktop.
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