GeneIT/geneit_app/src/api/ApiClient.ts

56 lines
1.3 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 {
const URL = process.env.REACT_APP_BACKEND ?? "";
if (URL.length === 0) throw new Error("Backend URL undefined!");
return URL;
}
/**
* Perform a request on the backend
*/
static async exec(args: {
uri: string;
method: "GET" | "POST" | "DELETE";
allowFail?: boolean;
jsonData?: any;
}): Promise<APIResponse> {
const res = await fetch(this.backendURL() + args.uri, {
method: args.method,
body: args.jsonData ? JSON.stringify(args.jsonData) : undefined,
headers: {
2023-06-09 09:19:40 +00:00
"X-auth-token": AuthApi.SignedIn ? AuthApi.AuthToken : "none",
2023-06-06 13:47:30 +00:00
"Content-Type": args.jsonData ? "application/json" : "text/plain",
},
});
let data;
if (res.headers.get("content-type") === "application/json")
data = await res.json();
else data = await res.blob();
if (!args.allowFail && !res.ok)
throw new ApiError("Request failed!", res.status, data);
return {
data: data,
status: res.status,
};
}
}