52 lines
1.3 KiB
TypeScript

import { AuthStatusRequest, AuthStatusResponse } from "../items";
export const apiFetch = async (
url: string,
options: RequestInit = {}
): Promise<Response> => {
const token = localStorage.getItem("token");
const headers = new Headers(options.headers);
if (token) {
headers.set("Authorization", `Bearer ${token}`);
}
const config = {
...options,
headers,
};
const response = await fetch(url, config);
if (!response.ok) {
if (response.status == 401) {
localStorage.removeItem("token");
window.location.href = "/";
}
throw new Error(`Request failed with status ${response.status}`);
}
return response;
};
export const get_auth_status = async (): Promise<AuthStatusResponse | null> => {
const token = localStorage.getItem("token") as string;
const req = AuthStatusRequest.create({ token });
const req_buffer = AuthStatusRequest.encode(req).finish();
const response = await apiFetch("/auth/get_auth_status", {
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
},
body: req_buffer,
});
const buffer = await response.arrayBuffer();
try {
const response = AuthStatusResponse.decode(new Uint8Array(buffer));
return response;
} catch (e) {
console.error("Failed to decode auth status:", e);
return null;
}
};