From 649c1a7b98e5f98f4f76c1d9f28d8e3085dde8a2 Mon Sep 17 00:00:00 2001 From: abefernan <44572727+abefernan@users.noreply.github.com> Date: Fri, 21 Jul 2023 19:51:17 +0200 Subject: [PATCH] Add requestJson --- lib/request.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 lib/request.ts 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())); +};