pronounsfu/frontend/lib/fetch.ts

33 lines
712 B
TypeScript
Raw Normal View History

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
) {
let headers = {};
2022-08-16 18:04:06 -07:00
const token =
typeof localStorage !== "undefined" &&
localStorage.getItem("pronouns-token");
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: {
...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();
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
}