Create fetch utility function

This commit is contained in:
thiloho
2024-09-25 21:45:01 +02:00
parent a9e2bd4cb7
commit bc5e494bbb
20 changed files with 525 additions and 700 deletions

View File

@@ -9,3 +9,48 @@ export const REGISTRATION_IS_DISABLED = dev
: process.env.REGISTRATION_IS_DISABLED
? JSON.parse(process.env.REGISTRATION_IS_DISABLED)
: false;
export const apiRequest = async (
customFetch: typeof fetch,
url: string,
method: "HEAD" | "GET" | "POST" | "PATCH" | "DELETE",
options: {
headers?: Record<string, string>;
body?: any;
successMessage?: string;
returnData?: boolean;
} = {
headers: {},
body: undefined,
successMessage: "Operation was successful",
returnData: false
}
) => {
const headers = {
"Content-Type": "application/json",
...options.headers
};
const response = await customFetch(url, {
method,
headers,
...(!["HEAD", "GET", "DELETE"].includes(method) && {
body: options.body instanceof ArrayBuffer ? options.body : JSON.stringify(options.body)
})
});
if (!response.ok) {
const errorData = await response.json();
return { success: false, message: errorData.message };
}
if (options.returnData) {
return {
success: true,
message: options.successMessage,
data: method === "HEAD" ? response : await response.json()
};
}
return { success: true, message: options.successMessage };
};

View File

@@ -177,7 +177,7 @@ export const handleImagePaste = async (event: ClipboardEvent, API_BASE_PREFIX: s
const response = await request.json();
if (JSON.parse(response.data)[1]) {
const fileId = JSON.parse(response.data)[3];
const fileId = JSON.parse(response.data)[4];
const fileUrl = `${API_BASE_PREFIX}/rpc/retrieve_file?id=${fileId}`;
const target = event.target as HTMLTextAreaElement;