cutt/src/api.ts
julius 8b4ee3b289
feat: Team management panel
the display name of a player is the same for all teams... change that?
2025-03-24 14:11:58 +01:00

123 lines
2.7 KiB
TypeScript

import { useSession } from "./Session";
export const baseUrl = import.meta.env.VITE_BASE_URL as string;
export async function apiAuth(
path: string,
data: any,
method: string = "GET"
): Promise<any> {
const req = new Request(`${baseUrl}api/${path}`, {
method: method,
headers: {
"Content-Type": "application/json",
},
credentials: "include",
...(data && { body: JSON.stringify(data) }),
});
let resp: Response;
try {
resp = await fetch(req);
} catch (e) {
throw new Error(`request failed: ${e}`);
}
if (!resp.ok) {
if (resp.status === 401) {
const { onLogout } = useSession();
onLogout();
throw new Error("Unauthorized");
}
}
const contentType = resp.headers.get("Content-Type");
switch (contentType) {
case "application/json":
return resp.json();
case "text/plain":
case "text/plain; charset=utf-8":
return resp.text();
case null:
return null;
default:
throw new Error(`Unsupported content type: ${contentType}`);
}
}
export type User = {
id: number;
username: string;
display_name: string;
email: string;
number: string;
scopes: string;
};
export async function currentUser(): Promise<User> {
const req = new Request(`${baseUrl}api/player/me`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
});
let resp: Response;
try {
resp = await fetch(req);
} catch (e) {
throw new Error(`request failed: ${e}`);
}
if (!resp.ok) {
if (resp.status === 401) {
logout();
throw new Error("Unauthorized");
}
}
return resp.json() as Promise<User>;
}
export async function loadPlayers(teamId: number) {
try {
const data = await apiAuth(`player/${teamId}/list`, null, "GET");
return data as User[];
} catch (error) {
console.error(error);
return null;
}
}
export type LoginRequest = {
username: string;
password: string;
};
export const login = async (req: LoginRequest): Promise<void> => {
try {
const response = await fetch(`${baseUrl}api/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams(req).toString(),
credentials: "include",
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
} catch (e) {
console.error(e);
throw e; // rethrow the error so it can be caught by the caller
}
};
export const logout = async () => {
try {
await fetch(`${baseUrl}api/logout`, {
method: "POST",
credentials: "include",
});
} catch (e) {
console.error(e);
}
};