Add requestJson

This commit is contained in:
abefernan
2023-07-21 19:51:17 +02:00
parent 1b5884924d
commit 649c1a7b98
+16
View File
@@ -0,0 +1,16 @@
export type RequestConfig = Omit<RequestInit, "body"> & { 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()));
};