2022-05-10 17:23:45 -07:00
|
|
|
import type { APIError } from "./types";
|
|
|
|
|
2022-09-15 15:49:04 -07:00
|
|
|
const apiBase = process.env.API_BASE ?? "/api";
|
2022-08-16 18:04:06 -07:00
|
|
|
|
2022-05-12 07:41:32 -07:00
|
|
|
export default async function fetchAPI<T>(
|
|
|
|
path: string,
|
|
|
|
method = "GET",
|
2022-07-05 13:21:28 -07:00
|
|
|
body: any = null
|
2022-05-12 07:41:32 -07:00
|
|
|
) {
|
2022-06-16 15:00:52 -07:00
|
|
|
let headers = {};
|
2022-08-16 18:04:06 -07:00
|
|
|
const token =
|
|
|
|
typeof localStorage !== "undefined" &&
|
|
|
|
localStorage.getItem("pronouns-token");
|
2022-06-16 15:00:52 -07:00
|
|
|
if (token) {
|
|
|
|
headers = {
|
|
|
|
Authorization: token,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-08-16 18:04:06 -07:00
|
|
|
const resp = await fetch(`${apiBase}/v1${path}`, {
|
2022-05-12 07:41:32 -07:00
|
|
|
method,
|
2022-05-10 17:23:45 -07:00
|
|
|
headers: {
|
2022-06-16 15:00:52 -07:00
|
|
|
...headers,
|
2022-05-10 17:23:45 -07:00
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
2022-05-12 07:41:32 -07:00
|
|
|
body: body ? JSON.stringify(body) : null,
|
2022-05-10 17:23:45 -07:00
|
|
|
});
|
|
|
|
|
2022-05-12 07:41:32 -07:00
|
|
|
const data = await resp.json();
|
2022-11-22 04:31:42 -08:00
|
|
|
if (resp.status < 200 || resp.status >= 300) throw data as APIError;
|
2022-05-12 07:41:32 -07:00
|
|
|
return data as T;
|
2022-05-10 17:23:45 -07:00
|
|
|
}
|