export const baseUrl = import.meta.env.VITE_BASE_URL as string; export const token = () => localStorage.getItem("access_token") as string; export default async function api(path: string, data: any): Promise { const request = new Request(`${baseUrl}${path}/`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); let response: Response; try { response = await fetch(request); } catch (e) { throw new Error(`request failed: ${e}`); } return response; } export async function apiAuth( path: string, data: any, method: string = "GET" ): Promise { const req = new Request(`${baseUrl}api/${path}`, { method: method, headers: { Authorization: `Bearer ${token()} `, "Content-Type": "application/json", }, ...(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) { logout(); throw new Error("Unauthorized"); } } return resp.json(); } export type User = { username: string; full_name: string; email: string; player_id: number; }; export async function currentUser(): Promise { if (!token()) throw new Error("you have no access token"); const req = new Request(`${baseUrl}api/users/me/`, { method: "GET", headers: { Authorization: `Bearer ${token()} `, "Content-Type": "application/json", }, }); 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; } export type LoginRequest = { username: string; password: string; }; export type Token = { access_token: string; token_type: string; }; export const login = (req: LoginRequest) => { fetch(`${baseUrl}api/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams(req).toString(), }) .then((resp) => resp.json() as Promise) .then((token) => token ? localStorage.setItem("access_token", token.access_token) : console.log("token not acquired") ) .catch((e) => console.log("catch error " + e + " in login")); return Promise; }; export const logout = () => localStorage.removeItem("access_token");