41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
|
|
import { z } from "zod/v4";
|
||
|
|
|
||
|
|
import {
|
||
|
|
type RemoteConnectionInput,
|
||
|
|
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,
|
||
|
|
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));
|
||
|
|
},
|
||
|
|
};
|