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