pronounsfu/frontend/src/lib/fetch.ts

30 lines
612 B
TypeScript
Raw Normal View History

2022-05-10 17:23:45 -07:00
import axios from "axios";
import type { APIError } from "./types";
2022-05-12 07:41:32 -07:00
export default async function fetchAPI<T>(
path: string,
method = "GET",
body = null
) {
let headers = {};
const token = localStorage.getItem("pronouns-token");
if (token) {
headers = {
Authorization: token,
};
}
2022-05-12 07:41:32 -07:00
const resp = await fetch(`/api/v1${path}`, {
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) throw data as APIError;
return data as T;
2022-05-10 17:23:45 -07:00
}