feat(!): return 204 instead of useless json responses, add fastFetch

This commit is contained in:
Sam 2023-03-30 16:05:40 +02:00
parent abc78f3a9a
commit 9c8b6a8f91
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
16 changed files with 63 additions and 31 deletions

View file

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { APIError } from "./entities";
import { PUBLIC_BASE_URL } from "$env/static/public";
@ -21,9 +22,36 @@ export async function apiFetch<T>(
});
const data = await resp.json();
if (resp.status < 200 || resp.status >= 300) throw data as APIError;
if (resp.status < 200 || resp.status >= 400) throw data as APIError;
return data as T;
}
export const apiFetchClient = async <T>(path: string, method: string = "GET", body: any = null) =>
export const apiFetchClient = async <T>(path: string, method = "GET", body: any = null) =>
apiFetch<T>(path, { method, body, token: localStorage.getItem("pronouns-token") || undefined });
/** Fetches the specified path without parsing the response body. */
export async function fastFetch(
path: string,
{
method,
body,
token,
headers,
}: { method?: string; body?: any; token?: string; headers?: Record<string, string> },
) {
const resp = await fetch(`${PUBLIC_BASE_URL}/api/v1${path}`, {
method: method || "GET",
headers: {
...(token ? { Authorization: token } : {}),
...(headers ? headers : {}),
"Content-Type": "application/json",
},
body: body ? JSON.stringify(body) : null,
});
if (resp.status < 200 || resp.status >= 400) throw (await resp.json()) as APIError;
}
/** Fetches the specified path without parsing the response body. */
export const fastFetchClient = async (path: string, method = "GET", body: any = null) =>
fastFetch(path, { method, body, token: localStorage.getItem("pronouns-token") || undefined });