63 lines
1.8 KiB
TypeScript
63 lines
1.8 KiB
TypeScript
import { useMutation, useQuery } from "@tanstack/react-query";
|
|
import { toast } from "sonner";
|
|
import { CAM_BASE } from "../utils/config";
|
|
|
|
const base_url = `${CAM_BASE}/api`;
|
|
|
|
const fetchCameraSideConfig = async ({ queryKey }: { queryKey: string[] }) => {
|
|
const [, cameraSide] = queryKey;
|
|
const fetchUrl = `${base_url}/fetch-config?id=${cameraSide}`;
|
|
const response = await fetch(fetchUrl, {
|
|
signal: AbortSignal.timeout(500),
|
|
});
|
|
if (!response.ok) throw new Error("cannot react cameraSide ");
|
|
return response.json();
|
|
};
|
|
|
|
const updateCamerasideConfig = async (data: {
|
|
id: string | number;
|
|
friendlyName: string;
|
|
cameraAddress: string;
|
|
}) => {
|
|
const updateUrl = `${base_url}/update-config?id=${data.id}`;
|
|
|
|
const updateConfigPayload = {
|
|
id: data.friendlyName,
|
|
fields: [
|
|
{
|
|
property: "propURI",
|
|
value: data.cameraAddress,
|
|
},
|
|
],
|
|
};
|
|
console.log(updateConfigPayload);
|
|
const response = await fetch(updateUrl, {
|
|
method: "POST",
|
|
body: JSON.stringify(updateConfigPayload),
|
|
});
|
|
if (!response.ok) throw new Error("Feature unavailable: Coming soon");
|
|
};
|
|
|
|
export const useFetchCameraConfig = (cameraSide: string) => {
|
|
const fetchedConfigQuery = useQuery({
|
|
queryKey: ["cameraSideConfig", cameraSide],
|
|
queryFn: fetchCameraSideConfig,
|
|
});
|
|
|
|
const updateConfigMutation = useMutation({
|
|
mutationKey: ["cameraSideConfigUpdate"],
|
|
mutationFn: updateCamerasideConfig,
|
|
onError: (error) => toast.error(error.message),
|
|
onSuccess: () => toast("Settings Successfully saved"),
|
|
});
|
|
|
|
return {
|
|
data: fetchedConfigQuery.data,
|
|
isPending: fetchedConfigQuery.isPending,
|
|
isError: fetchedConfigQuery.isError,
|
|
updateCameraConfig: updateConfigMutation.mutate,
|
|
updateCameraConfigError: updateConfigMutation.error,
|
|
updateCameraConfigLoading: updateConfigMutation.isPending,
|
|
};
|
|
};
|