mirror of
https://github.com/thiloho/archtika.git
synced 2025-11-22 10:51:36 +01:00
Create fetch utility function
This commit is contained in:
@@ -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 };
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user