A light fetch wrapper that returns errors as values.
import * as fetcher from '@safe-std/fetch';
import * as st from '@safe-std/error';
// Return errors as values
const res = await fetcher.query('http://localhost:3000', {
...
});
if (st.isErr(res)) {
// Unwrap thrown errors
const nativeErr = st.payload(res);
// Error names are fully typed
switch (nativeErr.name) {
case 'AbortError': ...;
case 'NotAllowedError': ...;
case 'TypeErr': ...;
}
} else {
res; // Response
}
// Fetch shorthand for methods
fetcher.get(...);
fetcher.post(...);
fetcher.put(...);
fetcher.del(...);
fetcher.patch(...);
...
if (st.isErr(res)) {
...
} else {
// Parse body as text
const body = await fetcher.text(res);
// Parse body as JSON
const body = await fetcher.json(res);
// Parse body as UInt8Array
const body = await fetcher.bytes(res);
// Parse body as ArrayBuffer
const body = await fetcher.buffer(res);
// Parse body as FormData
const body = await fetcher.form(res);
// Parse body as Blob
const body = await fetcher.blob(res);
}