38 lines
1.4 KiB
TypeScript
38 lines
1.4 KiB
TypeScript
import { z } from "zod/v4";
|
|
|
|
import type { ResourceInput } from "../common/inventory";
|
|
import { InventoryResponseSchema, ResourceResponseSchema } from "../common/inventory";
|
|
export const inventoryKeys = { company: (id: string) => ["resource-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/resources/${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: ResourceInput, token: string, id?: string) {
|
|
return ResourceResponseSchema.parse(
|
|
await request(`${companyId}${id ? `/${id}/update` : ""}`, { values }, token)
|
|
);
|
|
},
|
|
};
|