metis-desk/modules/companies/src/web/remote-connections/shared/api/remote-api.ts
2026-10-10 12:42:56 +02:00

47 lines
1.4 KiB
TypeScript

import { csrfFetch } from "@metis/core/client";
import { z } from "zod/v4";
import type { RemoteConnectionInput } from "../../../../common/remote-connections";
import {
RemoteConnectionResponseSchema,
RemoteConnectionsResponseSchema,
} from "../../../../common/remote-connections";
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, id?: string) {
const response = await csrfFetch(
`/api/remote-connections/${companyId}${id ? `/${id}/update` : ""}`,
{
method: values ? "POST" : "GET",
credentials: "same-origin",
headers: values ? { "content-type": "application/json" } : {},
...(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, id?: string) {
return RemoteConnectionResponseSchema.parse(await request(companyId, values, id));
},
};