metis-desk/modules/assets/src/web/inventory-api.ts

38 lines
1.3 KiB
TypeScript
Raw Normal View History

import { z } from "zod/v4";
import type { AssetInput } from "../common/inventory";
import { AssetResponseSchema, InventoryResponseSchema } from "../common/inventory";
export const inventoryKeys = { company: (id: string) => ["inventory", id] };
export class InventoryApiError extends Error {
constructor(public readonly code: string) {
super(code);
}
}
async function request(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;
}
export const inventoryApi = {
async get(companyId: string) {
return InventoryResponseSchema.parse(await request(companyId));
},
async save(companyId: string, values: AssetInput, token: string, id?: string) {
return AssetResponseSchema.parse(
await request(`${companyId}${id ? `/${id}/update` : ""}`, { values }, token)
);
},
};