pronounscc/src/lib/api/fetch.ts

25 lines
832 B
TypeScript
Raw Normal View History

2023-03-09 17:08:43 +01:00
import type { APIError } from "./entities";
2023-03-11 01:36:30 +01:00
export async function apiFetch<T>(
2023-03-09 17:08:43 +01:00
path: string,
{ method, body, token }: { method?: string; body?: any; token?: string },
) {
2023-03-11 01:36:30 +01:00
const apiBase = typeof process !== "undefined" ? process.env.ORIGIN : "";
const resp = await fetch(`${apiBase}/api/v1${path}`, {
method: method || "GET",
2023-03-09 17:08:43 +01:00
headers: {
...(token ? { Authorization: token } : {}),
"Content-Type": "application/json",
},
body: body ? JSON.stringify(body) : null,
});
const data = await resp.json();
if (resp.status < 200 || resp.status >= 300) throw data as APIError;
return data as T;
}
2023-03-11 01:36:30 +01:00
export const apiFetchClient = async <T>(path: string, method: string = "GET", body: any = null) =>
apiFetch<T>(path, { method, body, token: localStorage.getItem("pronouns-token") || undefined });