tsuite
Version:
A collection of useful utility functions, All fully typed and documented
31 lines (29 loc) • 1.03 kB
JavaScript
/**
* tsuite v0.7.2
* tijn.dev
* @license MIT
**/
import { tryCatch } from "typecatch";
//#region src/effetch.ts
/**
* Effective fetch
*
* Sends the request and returns the response as parsed JSON (or text).
*
* @template T The expected type of the JSON response
* @returns A promise that resolves to the parsed JSON or text data
* @throws If the fetch request fails or if the JSON parsing fails
*/
async function effetch(input, init) {
const fetchFunction = init?.event?.fetch || fetch;
const res = await tryCatch(fetchFunction(input, init));
if (res.error) throw new Error(`Failed to fetch: ${res.error}`);
if (!res.data) throw new Error("Request sending failed unexpectedly.");
if (!res.data.ok) throw new Error(`HTTP error! status: ${res.data?.status} ${res.data?.statusText}`);
if (init?.responseType === "text") return res.data.text();
const parse = await tryCatch(res.data.json());
if (parse.error) throw new Error(`Failed to parse JSON: ${parse.error}`);
return parse.data;
}
//#endregion
export { effetch };