import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Textarea } from "@/components/ui/textarea"; import { api } from "@/utils/api"; import { AlertBlock } from "@/components/shared/alert-block"; import { zodResolver } from "@hookform/resolvers/zod"; import { useEffect } from "react"; import { useForm } from "react-hook-form"; import { toast } from "sonner"; import { z } from "zod"; import jsyaml from "js-yaml"; const UpdateTraefikConfigSchema = z.object({ traefikConfig: z.string(), }); type UpdateTraefikConfig = z.infer; interface Props { applicationId: string; } export const validateAndFormatYAML = (yamlText: string) => { try { const obj = jsyaml.load(yamlText); const formattedYaml = jsyaml.dump(obj, { indent: 4 }); return { valid: true, formattedYaml, error: null }; } catch (error) { if (error instanceof jsyaml.YAMLException) { return { valid: false, formattedYaml: yamlText, error: error.message, }; } return { valid: false, formattedYaml: yamlText, error: "An unexpected error occurred while processing the YAML.", }; } }; export const UpdateTraefikConfig = ({ applicationId }: Props) => { const { data, refetch } = api.application.readTraefikConfig.useQuery( { applicationId, }, { enabled: !!applicationId }, ); const { mutateAsync, isLoading, error, isError } = api.application.updateTraefikConfig.useMutation(); const form = useForm({ defaultValues: { traefikConfig: "", }, resolver: zodResolver(UpdateTraefikConfigSchema), }); useEffect(() => { if (data) { form.reset({ traefikConfig: data || "", }); } }, [form, form.reset, data]); const onSubmit = async (data: UpdateTraefikConfig) => { const { valid, error } = validateAndFormatYAML(data.traefikConfig); if (!valid) { form.setError("traefikConfig", { type: "manual", message: error || "Invalid YAML", }); return; } form.clearErrors("traefikConfig"); await mutateAsync({ applicationId, traefikConfig: data.traefikConfig, }) .then(async () => { toast.success("Traefik config Updated"); refetch(); }) .catch(() => { toast.error("Error to update the traefik config"); }); }; return ( Update traefik config Update the traefik config {isError && {error?.message}}
( Traefik config