GeneIT/geneit_app/src/api/ApiClient.ts

85 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-06-09 09:19:40 +00:00
import { AuthApi } from "./AuthApi";
2023-06-06 13:47:30 +00:00
interface APIResponse {
data: any;
status: number;
}
export class ApiError extends Error {
constructor(message: string, public code: number, public data: any) {
super(message);
}
}
export class APIClient {
/**
* Get backend URL
*/
static backendURL(): string {
2023-12-12 18:37:41 +00:00
const URL = import.meta.env.VITE_APP_BACKEND ?? "";
2023-06-06 13:47:30 +00:00
if (URL.length === 0) throw new Error("Backend URL undefined!");
return URL;
}
/**
* Check out whether the backend is accessed through
* HTTPS or not
*/
static IsBackendSecure(): boolean {
return this.backendURL().startsWith("https");
}
2023-06-06 13:47:30 +00:00
/**
* Perform a request on the backend
*/
static async exec(args: {
uri: string;
method: "GET" | "POST" | "DELETE" | "PATCH" | "PUT";
2023-06-06 13:47:30 +00:00
allowFail?: boolean;
jsonData?: any;
2023-08-10 10:10:09 +00:00
formData?: FormData;
2023-06-06 13:47:30 +00:00
}): Promise<APIResponse> {
2023-08-10 10:10:09 +00:00
let body = undefined;
let headers: any = {
"X-auth-token": AuthApi.SignedIn ? AuthApi.AuthToken : "none",
};
// JSON request
if (args.jsonData) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(args.jsonData);
}
// Form data request
else if (args.formData) {
body = args.formData;
}
2023-06-06 13:47:30 +00:00
const res = await fetch(this.backendURL() + args.uri, {
method: args.method,
2023-08-10 10:10:09 +00:00
body: body,
headers: headers,
2023-06-06 13:47:30 +00:00
});
2023-08-10 10:10:09 +00:00
// Process response
2023-06-06 13:47:30 +00:00
let data;
if (res.headers.get("content-type") === "application/json")
data = await res.json();
else data = await res.blob();
2023-06-13 13:29:15 +00:00
// Handle expired tokens
if (res.status === 412) {
AuthApi.RemoveAuthToken();
2023-06-14 12:14:46 +00:00
window.location.href = "/";
2023-06-13 13:29:15 +00:00
}
2023-06-06 13:47:30 +00:00
if (!args.allowFail && !res.ok)
throw new ApiError("Request failed!", res.status, data);
return {
data: data,
status: res.status,
};
}
}