metis-desk/modules/companies/src/web/remote-connections/shared/api/remote-api.ts

41 lines
1.4 KiB
TypeScript
Raw Normal View History

2026-10-06 16:44:21 +00:00
import { z } from "zod/v4";
import type { RemoteConnectionInput } from "../../../../common/remote-connections";
2026-10-06 16:44:21 +00:00
import {
RemoteConnectionResponseSchema,
RemoteConnectionsResponseSchema,
} from "../../../../common/remote-connections";
2026-10-06 16:44:21 +00:00
export const remoteKeys = { company: (id: string) => ["remote-connections", id] };
export class RemoteApiError extends Error {
constructor(public readonly code: string) {
super(code);
}
}
async function request(
companyId: string,
values?: RemoteConnectionInput,
token?: string,
id?: string
) {
const response = await fetch(`/api/remote-connections/${companyId}${id ? `/${id}/update` : ""}`, {
method: values ? "POST" : "GET",
credentials: "same-origin",
headers: values ? { "content-type": "application/json", "x-csrf-token": token ?? "" } : {},
...(values ? { body: JSON.stringify({ values }) } : {}),
});
const body: unknown = await response.json();
if (!response.ok) {
const error = z.object({ code: z.string() }).safeParse(body);
throw new RemoteApiError(error.success ? error.data.code : "INTERNAL_ERROR");
}
return body;
}
export const remoteApi = {
async get(companyId: string) {
return RemoteConnectionsResponseSchema.parse(await request(companyId));
},
async save(companyId: string, values: RemoteConnectionInput, token: string, id?: string) {
return RemoteConnectionResponseSchema.parse(await request(companyId, values, token, id));
},
};