56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
|
|
export type User = {
|
||
|
|
id: string;
|
||
|
|
tag: string;
|
||
|
|
avatar_url: string;
|
||
|
|
};
|
||
|
|
|
||
|
|
export type PartialGuild = {
|
||
|
|
id: string;
|
||
|
|
name: string;
|
||
|
|
icon_url: string;
|
||
|
|
bot_in_guild: boolean;
|
||
|
|
};
|
||
|
|
|
||
|
|
export type CurrentUser = {
|
||
|
|
user: User;
|
||
|
|
guilds: PartialGuild[];
|
||
|
|
};
|
||
|
|
|
||
|
|
export type AuthCallback = CurrentUser & { token: string };
|
||
|
|
|
||
|
|
export type ApiError = {
|
||
|
|
error_code: string;
|
||
|
|
message: string;
|
||
|
|
};
|
||
|
|
|
||
|
|
export const TOKEN_KEY = "catalogger-token";
|
||
|
|
|
||
|
|
export default async function apiFetch<T>(
|
||
|
|
method: "GET" | "POST" | "PATCH" | "DELETE",
|
||
|
|
path: string,
|
||
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
|
|
body: any = null,
|
||
|
|
) {
|
||
|
|
const token = localStorage.getItem(TOKEN_KEY);
|
||
|
|
const headers = {
|
||
|
|
...(body != null
|
||
|
|
? { "Content-Type": "application/json; charset=utf-8" }
|
||
|
|
: {}),
|
||
|
|
...(token ? { Authorization: token } : {}),
|
||
|
|
};
|
||
|
|
|
||
|
|
const reqBody = body ? JSON.stringify(body) : undefined;
|
||
|
|
|
||
|
|
console.debug("Sending", method, "request to", path, "with body", reqBody);
|
||
|
|
|
||
|
|
const resp = await fetch(path, {
|
||
|
|
method,
|
||
|
|
body: body ? JSON.stringify(body) : undefined,
|
||
|
|
headers,
|
||
|
|
});
|
||
|
|
if (resp.status < 200 || resp.status > 299)
|
||
|
|
throw (await resp.json()) as ApiError;
|
||
|
|
|
||
|
|
return (await resp.json()) as T;
|
||
|
|
}
|