Add requestJson
This commit is contained in:
@@ -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()));
|
||||
};
|
||||
Reference in New Issue
Block a user