refactor(networks): update network form schema and enhance handling logic

- Replaced zodResolver with standardSchemaResolver for improved schema validation.
- Added new toggle options for network settings, enhancing user interface clarity.
- Refactored network creation and update logic to streamline payload handling.
- Updated network form schema to remove default values, ensuring explicit user input.
- Introduced SERVER_LOCAL sentinel for local Dokploy server identification.
This commit is contained in:
Mauricio Siu
2026-07-21 21:46:40 -06:00
parent f4bcc2e8a8
commit 736a77e112
2 changed files with 174 additions and 222 deletions
@@ -1,7 +1,7 @@
"use client"; "use client";
import { zodResolver } from "@hookform/resolvers/zod"; import { standardSchemaResolver as zodResolver } from "@hookform/resolvers/standard-schema";
import { Network, Pencil, Plus } from "lucide-react"; import { Network, Pencil, Plus, Trash2 } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useFieldArray, useForm } from "react-hook-form"; import { useFieldArray, useForm } from "react-hook-form";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -47,6 +47,8 @@ const networkDriverEnum = [
/** Sentinel for "no scope" */ /** Sentinel for "no scope" */
const SCOPE_EMPTY = "__scope_none__"; const SCOPE_EMPTY = "__scope_none__";
/** Sentinel for the local Dokploy server (no serverId) */
const SERVER_LOCAL = "__server_local__";
const ipamConfigEntrySchema = z.object({ const ipamConfigEntrySchema = z.object({
subnet: z.string().optional(), subnet: z.string().optional(),
@@ -56,17 +58,17 @@ const ipamConfigEntrySchema = z.object({
const networkFormSchema = z.object({ const networkFormSchema = z.object({
name: z.string().min(1, "Name is required"), name: z.string().min(1, "Name is required"),
driver: z.enum(networkDriverEnum).default("bridge"), driver: z.enum(networkDriverEnum),
scope: z.string().optional(), scope: z.string().optional(),
serverId: z.string().optional(), serverId: z.string().optional(),
internal: z.boolean().default(false), internal: z.boolean(),
attachable: z.boolean().default(false), attachable: z.boolean(),
ingress: z.boolean().default(false), ingress: z.boolean(),
configOnly: z.boolean().default(false), configOnly: z.boolean(),
enableIPv4: z.boolean().default(true), enableIPv4: z.boolean(),
enableIPv6: z.boolean().default(false), enableIPv6: z.boolean(),
ipamDriver: z.string().optional(), ipamDriver: z.string().optional(),
ipamConfig: z.array(ipamConfigEntrySchema).default([]), ipamConfig: z.array(ipamConfigEntrySchema),
}); });
type NetworkFormValues = z.infer<typeof networkFormSchema>; type NetworkFormValues = z.infer<typeof networkFormSchema>;
@@ -86,6 +88,39 @@ const defaultValues: NetworkFormValues = {
ipamConfig: [], ipamConfig: [],
}; };
const toggleOptions = [
{
name: "internal",
label: "Internal",
description: "Containers on this network cannot reach external networks.",
},
{
name: "attachable",
label: "Attachable",
description: "Allow standalone containers to attach to this network.",
},
{
name: "enableIPv4",
label: "Enable IPv4",
description: "Enable IPv4 addressing on the network.",
},
{
name: "enableIPv6",
label: "Enable IPv6",
description: "Enable IPv6 addressing on the network.",
},
{
name: "ingress",
label: "Ingress",
description: "Use as the routing-mesh network in Swarm mode.",
},
{
name: "configOnly",
label: "Config only",
description: "Placeholder network whose config is reused by others.",
},
] as const;
interface HandleNetworkProps { interface HandleNetworkProps {
networkId?: string; networkId?: string;
children?: React.ReactNode; children?: React.ReactNode;
@@ -104,9 +139,9 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
{ enabled: isEdit && !!networkId }, { enabled: isEdit && !!networkId },
); );
const { mutateAsync, isLoading: isPending } = networkId const createMutation = api.network.create.useMutation();
? api.network.update.useMutation() const updateMutation = api.network.update.useMutation();
: api.network.create.useMutation(); const isPending = isEdit ? updateMutation.isPending : createMutation.isPending;
const form = useForm<NetworkFormValues>({ const form = useForm<NetworkFormValues>({
resolver: zodResolver(networkFormSchema), resolver: zodResolver(networkFormSchema),
@@ -148,9 +183,7 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
const scope = const scope =
data.scope && data.scope !== SCOPE_EMPTY ? data.scope : undefined; data.scope && data.scope !== SCOPE_EMPTY ? data.scope : undefined;
try { const payload = {
await mutateAsync({
networkId: networkId ?? "",
name: data.name, name: data.name,
driver: data.driver, driver: data.driver,
scope, scope,
@@ -165,8 +198,16 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
driver: data.ipamDriver, driver: data.ipamDriver,
config: data.ipamConfig, config: data.ipamConfig,
}, },
}); };
try {
if (isEdit && networkId) {
await updateMutation.mutateAsync({ networkId, ...payload });
} else {
await createMutation.mutateAsync(payload);
}
toast.success(isEdit ? "Network updated" : "Network created");
await utils.network.all.invalidate(); await utils.network.all.invalidate();
if (networkId) await utils.network.one.invalidate({ networkId }); if (networkId) await utils.network.one.invalidate({ networkId });
setIsOpen(false); setIsOpen(false);
@@ -193,7 +234,7 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
return ( return (
<Dialog open={isOpen} onOpenChange={setIsOpen}> <Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>{trigger}</DialogTrigger> <DialogTrigger asChild>{trigger}</DialogTrigger>
<DialogContent className="sm:max-w-xl max-h-[90vh] overflow-y-auto"> <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
<Network className="size-5 text-muted-foreground" /> <Network className="size-5 text-muted-foreground" />
@@ -257,6 +298,7 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
)} )}
/> />
</div> </div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<FormField <FormField
control={form.control} control={form.control}
name="serverId" name="serverId"
@@ -264,8 +306,14 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
<FormItem> <FormItem>
<FormLabel>Server</FormLabel> <FormLabel>Server</FormLabel>
<Select <Select
onValueChange={field.onChange} onValueChange={(value) =>
value={field.value ?? undefined} field.onChange(
value === SERVER_LOCAL ? undefined : value,
)
}
value={
field.value ?? (isCloud ? undefined : SERVER_LOCAL)
}
> >
<FormControl> <FormControl>
<SelectTrigger> <SelectTrigger>
@@ -274,7 +322,7 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
</FormControl> </FormControl>
<SelectContent> <SelectContent>
{!isCloud && ( {!isCloud && (
<SelectItem value={undefined}> <SelectItem value={SERVER_LOCAL}>
Dokploy server Dokploy server
</SelectItem> </SelectItem>
)} )}
@@ -291,7 +339,7 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
<FormDescription className="text-muted-foreground"> <FormDescription className="text-muted-foreground">
{isCloud {isCloud
? "Server where this network will be created." ? "Server where this network will be created."
: "Dokploy server is the default local server; or choose a specific server."} : "Dokploy server is the default local server."}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -322,17 +370,19 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
</FormItem> </FormItem>
)} )}
/> />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{toggleOptions.map((option) => (
<FormField <FormField
key={option.name}
control={form.control} control={form.control}
name="internal" name={option.name}
render={({ field }) => ( render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4"> <FormItem className="flex flex-row items-start justify-between gap-3 space-y-0 rounded-lg border p-4">
<div className="space-y-0.5"> <div className="space-y-1 pr-1">
<FormLabel className="text-base">Internal</FormLabel> <FormLabel>{option.label}</FormLabel>
<FormDescription className="text-muted-foreground"> <FormDescription className="text-muted-foreground">
Restrict external access; containers on this network {option.description}
cannot reach external networks.
</FormDescription> </FormDescription>
</div> </div>
<FormControl> <FormControl>
@@ -344,112 +394,15 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
</FormItem> </FormItem>
)} )}
/> />
<FormField ))}
control={form.control}
name="attachable"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Attachable</FormLabel>
<FormDescription className="text-muted-foreground">
Allow standalone containers to attach to this network
(e.g. in Swarm, not only services).
</FormDescription>
</div> </div>
<FormControl> <div className="space-y-4 rounded-lg border p-4">
<Switch <div className="space-y-1">
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="enableIPv4"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Enable IPv4</FormLabel>
<FormDescription className="text-muted-foreground">
Enable IPv4 addressing on the network.
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="enableIPv6"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Enable IPv6</FormLabel>
<FormDescription className="text-muted-foreground">
Enable IPv6 addressing on the network.
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="ingress"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Ingress</FormLabel>
<FormDescription className="text-muted-foreground">
Use as the routing-mesh network in Swarm mode (load
balancing between nodes).
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="configOnly"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Config only</FormLabel>
<FormDescription className="text-muted-foreground">
Create a placeholder network whose config is reused by
other networks; cannot run containers on it.
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</div>
<div className="space-y-2 rounded-lg border p-4">
<FormLabel>IPAM</FormLabel> <FormLabel>IPAM</FormLabel>
<p className="text-sm text-muted-foreground">
IP address management settings for this network.
</p>
</div>
<FormField <FormField
control={form.control} control={form.control}
name="ipamDriver" name="ipamDriver"
@@ -514,9 +467,10 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
type="button" type="button"
variant="outline" variant="outline"
size="icon" size="icon"
aria-label="Remove IPAM config"
onClick={() => ipamConfigFieldArray.remove(index)} onClick={() => ipamConfigFieldArray.remove(index)}
> >
− <Trash2 className="size-4" />
</Button> </Button>
</div> </div>
))} ))}
@@ -532,6 +486,7 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
}) })
} }
> >
<Plus className="size-4" />
Add IPAM config Add IPAM config
</Button> </Button>
</div> </div>
@@ -544,14 +499,8 @@ export const HandleNetwork = ({ networkId, children }: HandleNetworkProps) => {
> >
Cancel Cancel
</Button> </Button>
<Button type="submit" disabled={isPending}> <Button type="submit" isLoading={isPending}>
{isPending {isEdit ? "Update network" : "Create network"}
? isEdit
? "Updating…"
: "Creating…"
: isEdit
? "Update network"
: "Create network"}
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>
+5 -2
View File
@@ -6,6 +6,7 @@ import {
} from "@dokploy/server/db/schema"; } from "@dokploy/server/db/schema";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import type { z } from "zod";
import { IS_CLOUD } from "../constants"; import { IS_CLOUD } from "../constants";
import { getRemoteDocker } from "../utils/servers/remote-docker"; import { getRemoteDocker } from "../utils/servers/remote-docker";
@@ -27,7 +28,7 @@ export const findNetworkById = async (networkId: string) => {
}; };
export const createNetwork = async ( export const createNetwork = async (
input: typeof apiCreateNetwork._type, input: z.infer<typeof apiCreateNetwork>,
organizationId: string, organizationId: string,
) => { ) => {
if (IS_CLOUD) { if (IS_CLOUD) {
@@ -86,7 +87,9 @@ export const createNetwork = async (
return created; return created;
}; };
export const updateNetwork = async (input: typeof apiUpdateNetwork._type) => { export const updateNetwork = async (
input: z.infer<typeof apiUpdateNetwork>,
) => {
const { networkId, ...rest } = input; const { networkId, ...rest } = input;
const [updated] = await db const [updated] = await db
.update(network) .update(network)