diff --git a/lib/request.ts b/lib/request.ts new file mode 100644 index 0000000..3cd002e --- /dev/null +++ b/lib/request.ts @@ -0,0 +1,16 @@ +export type RequestConfig = Omit & { body?: unknown }; + +export const requestJson = async ( + endpoint: string, + { method, headers, body, ...restConfig }: RequestConfig = {}, +) => { + const config: RequestInit = { + method: method ?? body ? "POST" : "GET", + headers: { "Content-Type": "application/json", ...headers }, + body: body ? JSON.stringify(body) : null, + ...restConfig, + }; + + const response = await fetch(endpoint, config); + return response.ok ? response.json() : Promise.reject(new Error(await response.text())); +};