1import type { NodeType } from "@marzneshin/features/nodes";
2import { useMutation } from "@tanstack/react-query";
3import { fetch, queryClient } from "@marzneshin/utils";
4import { toast } from "sonner";
5import i18n from "@marzneshin/features/i18n";
6import {
7 type NodeBackendSettingConfigFormat,
8 NodesSettingsQueryFetchKey,
9} from "./settings.query";
10
11interface UpdateNodesSettings {
12 node: NodeType;
13 backend: string;
14 config: string;
15 format: NodeBackendSettingConfigFormat;
16}
17
18export async function fetchUpdateNodesSettings({
19 node,
20 backend,
21 config,
22 format,
23}: UpdateNodesSettings): Promise<NodeType> {
24 return fetch(`/nodes/${node.id}/${backend}/config`, {
25 method: "put",
26 body: { config, format },
27 }).then((node) => {
28 return node;
29 });
30}
31
32const handleError = (error: Error, value: UpdateNodesSettings) => {
33 toast.error(i18n.t("events.update.error", { name: value.node.name }), {
34 description: error.message,
35 });
36};
37
38const handleSuccess = (value: NodeType) => {
39 toast.success(i18n.t("events.update.success.title", { name: value.name }), {
40 description: i18n.t("events.update.success.desc"),
41 });
42 queryClient.invalidateQueries({ queryKey: [NodesSettingsQueryFetchKey] });
43};
44
45const NodesSettingsUpdateFetchKey = ["nodes", "config"];
46
47export const useNodesSettingsMutation = () => {
48 return useMutation({
49 mutationKey: NodesSettingsUpdateFetchKey,
50 mutationFn: fetchUpdateNodesSettings,
51 onError: handleError,
52 onSuccess: handleSuccess,
53 });
54};