22 lines
765 B
TypeScript
22 lines
765 B
TypeScript
|
|
import { z } from "zod/v4";
|
||
|
|
|
||
|
|
import { InventoryApiError } from "./inventory-api-error";
|
||
|
|
|
||
|
|
export async function inventoryRequest(path: string, body?: unknown, csrfToken?: string) {
|
||
|
|
const response = await fetch(`/api/assets/${path}`, {
|
||
|
|
method: body === undefined ? "GET" : "POST",
|
||
|
|
credentials: "same-origin",
|
||
|
|
headers:
|
||
|
|
body === undefined
|
||
|
|
? {}
|
||
|
|
: { "content-type": "application/json", "x-csrf-token": csrfToken ?? "" },
|
||
|
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||
|
|
});
|
||
|
|
const data: unknown = await response.json();
|
||
|
|
if (!response.ok) {
|
||
|
|
const error = z.object({ code: z.string() }).safeParse(data);
|
||
|
|
throw new InventoryApiError(error.success ? error.data.code : "INTERNAL_ERROR");
|
||
|
|
}
|
||
|
|
return data;
|
||
|
|
}
|