55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
import { useMutation, useQuery, type QueryFunctionContext } from "@tanstack/react-query";
|
|
import { CAM_BASE } from "../utils/config";
|
|
import type { zoomConfig, ZoomInOptions } from "../types/types";
|
|
import { toast } from "sonner";
|
|
import { useEffect } from "react";
|
|
|
|
async function zoomIn(options: ZoomInOptions) {
|
|
console.log(options);
|
|
const response = await fetch(
|
|
`${CAM_BASE}/Ip${options.camera}-command?magnification=${options.multiplierText?.toLowerCase()}`,
|
|
{
|
|
signal: AbortSignal.timeout(500),
|
|
}
|
|
);
|
|
if (!response.ok) {
|
|
throw new Error("Cannot reach camera zoom endpoint");
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
async function fetchZoomInConfig({ queryKey }: QueryFunctionContext<[string, zoomConfig]>) {
|
|
const [, { camera }] = queryKey;
|
|
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Ip${camera}`, {
|
|
signal: AbortSignal.timeout(500),
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error("Cannot get camera zoom settings");
|
|
}
|
|
return response.json();
|
|
}
|
|
//change to string
|
|
export const useCameraZoom = (options: zoomConfig) => {
|
|
const mutation = useMutation({
|
|
mutationKey: ["zoomIn"],
|
|
mutationFn: (options: ZoomInOptions) => zoomIn(options),
|
|
onError: (err) => {
|
|
toast.error(`Failed to update zoom settings: ${err.message}`, {
|
|
id: "zoom",
|
|
});
|
|
},
|
|
});
|
|
|
|
const query = useQuery({
|
|
queryKey: ["fetchZoomInConfig", options],
|
|
queryFn: fetchZoomInConfig,
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (query.isError) toast.error(query.error.message, { id: "zoom" });
|
|
}, [query?.error?.message, query.isError]);
|
|
|
|
return { mutation, query };
|
|
};
|