refactor uptime forms'
This commit is contained in:
1 parent
4ed89ace23
commit
16aec18c28
9 files changed
+137
-110
No files matched your search
@@ -1,32 +1,56 @@
|
|||||||
import { monitorSchema } from "@/validation/zod";
|
|
||||||
import ms from "ms";
|
|
||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
|
import humanInterval from "human-interval";
|
||||||
|
import type { FormValues, SubmitValues } from "@/pages/uptime/UptimeForm";
|
||||||
|
import type { IMonitor } from "@/types/monitor";
|
||||||
|
|
||||||
|
import ms from "ms";
|
||||||
|
|
||||||
import { z } from "zod";
|
|
||||||
export const useInitForm = ({
|
export const useInitForm = ({
|
||||||
initialData,
|
initialData,
|
||||||
}: {
|
}: {
|
||||||
initialData: Partial<z.infer<typeof monitorSchema>> | undefined;
|
initialData: IMonitor | undefined;
|
||||||
}) => {
|
}) => {
|
||||||
return useMemo(() => {
|
return useMemo(() => {
|
||||||
let humanInterval = "1 minute";
|
const apiToForm = (apiData: IMonitor): FormValues => {
|
||||||
if (initialData?.interval) {
|
return {
|
||||||
const parsed = Number(initialData.interval);
|
type: apiData.type,
|
||||||
if (!isNaN(parsed)) {
|
url: apiData.url,
|
||||||
humanInterval = ms(parsed, { long: true });
|
port: apiData.port,
|
||||||
}
|
n: apiData.n,
|
||||||
}
|
notificationChannels: apiData.notificationChannels,
|
||||||
|
name: apiData.name,
|
||||||
const defaults: z.infer<typeof monitorSchema> = {
|
interval: ms(apiData.interval, { long: true }),
|
||||||
type: initialData?.type || "https",
|
rejectUnauthorized: apiData.rejectUnauthorized,
|
||||||
url: initialData?.url || "",
|
};
|
||||||
port: initialData?.port || 80,
|
|
||||||
n: initialData?.n || 3,
|
|
||||||
notificationChannels: initialData?.notificationChannels || [],
|
|
||||||
name: initialData?.name || "",
|
|
||||||
interval: humanInterval,
|
|
||||||
rejectUnauthorized: initialData?.rejectUnauthorized ?? true,
|
|
||||||
};
|
};
|
||||||
return { defaults };
|
|
||||||
|
const formToApi = (formData: FormValues): SubmitValues => {
|
||||||
|
const submitData: SubmitValues = {
|
||||||
|
type: formData.type,
|
||||||
|
url: formData.url,
|
||||||
|
port: formData.type === "port" ? formData.port : undefined,
|
||||||
|
n: formData.n,
|
||||||
|
notificationChannels: formData.notificationChannels,
|
||||||
|
name: formData.name,
|
||||||
|
interval: humanInterval(formData.interval),
|
||||||
|
rejectUnauthorized: formData.rejectUnauthorized,
|
||||||
|
};
|
||||||
|
|
||||||
|
return submitData;
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaults: FormValues = initialData
|
||||||
|
? apiToForm(initialData)
|
||||||
|
: {
|
||||||
|
type: "https",
|
||||||
|
url: "",
|
||||||
|
port: 80,
|
||||||
|
n: 3,
|
||||||
|
notificationChannels: [],
|
||||||
|
name: "",
|
||||||
|
interval: "1 minute",
|
||||||
|
rejectUnauthorized: true,
|
||||||
|
};
|
||||||
|
return { defaults, apiToForm, formToApi };
|
||||||
}, [initialData]);
|
}, [initialData]);
|
||||||
};
|
};
|
||||||
@@ -2,7 +2,7 @@ import { PageSpeedForm } from "@/pages/pagespeed/PageSpeedForm";
|
|||||||
|
|
||||||
import humanInterval from "human-interval";
|
import humanInterval from "human-interval";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { monitorSchema } from "@/validation/zod";
|
import { monitorSchema } from "@/validation";
|
||||||
import { useGet, usePost } from "@/hooks/UseApi";
|
import { useGet, usePost } from "@/hooks/UseApi";
|
||||||
import type { ApiResponse } from "@/types/api";
|
import type { ApiResponse } from "@/types/api";
|
||||||
import { useNavigate } from "react-router";
|
import { useNavigate } from "react-router";
|
||||||
|
|||||||
@@ -1,21 +1,14 @@
|
|||||||
import { monitorSchema } from "@/validation/zod";
|
|
||||||
import { useGet, usePatch } from "@/hooks/UseApi";
|
import { useGet, usePatch } from "@/hooks/UseApi";
|
||||||
import { UptimeForm } from "@/pages/uptime/UptimeForm";
|
import { UptimeForm } from "@/pages/uptime/UptimeForm";
|
||||||
|
|
||||||
import { useParams } from "react-router";
|
import { useParams } from "react-router";
|
||||||
import type { ApiResponse } from "@/types/api";
|
import type { ApiResponse } from "@/types/api";
|
||||||
import humanInterval from "human-interval";
|
|
||||||
import { z } from "zod";
|
|
||||||
import { useNavigate } from "react-router";
|
import { useNavigate } from "react-router";
|
||||||
import type { INotificationChannel } from "@/types/notification-channel";
|
import type { INotificationChannel } from "@/types/notification-channel";
|
||||||
import type { IMonitor } from "@/types/monitor";
|
import type { IMonitor } from "@/types/monitor";
|
||||||
|
import type { SubmitValues } from "@/pages/uptime/UptimeForm";
|
||||||
|
|
||||||
const UptimeConfigurePage = () => {
|
const UptimeConfigurePage = () => {
|
||||||
type FormValues = z.infer<typeof monitorSchema>;
|
|
||||||
type SubmitValues = Omit<FormValues, "interval"> & {
|
|
||||||
interval: number | undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
|
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
|
||||||
@@ -24,23 +17,17 @@ const UptimeConfigurePage = () => {
|
|||||||
const { response: monitorResponse } = useGet<ApiResponse<IMonitor>>(
|
const { response: monitorResponse } = useGet<ApiResponse<IMonitor>>(
|
||||||
`/monitors/${id}`
|
`/monitors/${id}`
|
||||||
);
|
);
|
||||||
const monitor = monitorResponse?.data || {};
|
const monitor = monitorResponse?.data;
|
||||||
const notificationOptions = response?.data ?? [];
|
const notificationOptions = response?.data ?? [];
|
||||||
|
|
||||||
const { patch, loading, error } = usePatch<Partial<SubmitValues>, IMonitor>();
|
const { patch, loading, error } = usePatch<Partial<SubmitValues>, IMonitor>();
|
||||||
|
|
||||||
const onSubmit = async (data: FormValues) => {
|
if (!monitor) {
|
||||||
let interval = humanInterval(data.interval);
|
return null;
|
||||||
if (!interval) interval = 60000;
|
}
|
||||||
const submitData = {
|
|
||||||
type: data.type,
|
const onSubmit = async (data: SubmitValues) => {
|
||||||
name: data.name,
|
const result = await patch(`/monitors/${id}`, data);
|
||||||
n: data.n,
|
|
||||||
notificationChannels: data.notificationChannels,
|
|
||||||
interval,
|
|
||||||
rejectUnauthorized: data.rejectUnauthorized,
|
|
||||||
};
|
|
||||||
const result = await patch(`/monitors/${id}`, submitData);
|
|
||||||
if (result) {
|
if (result) {
|
||||||
navigate(`/uptime/${id}`);
|
navigate(`/uptime/${id}`);
|
||||||
} else {
|
} else {
|
||||||
@@ -50,9 +37,7 @@ const UptimeConfigurePage = () => {
|
|||||||
return (
|
return (
|
||||||
<UptimeForm
|
<UptimeForm
|
||||||
mode="configure"
|
mode="configure"
|
||||||
initialData={{
|
initialData={monitor}
|
||||||
...monitor,
|
|
||||||
}}
|
|
||||||
onSubmit={onSubmit}
|
onSubmit={onSubmit}
|
||||||
notificationOptions={notificationOptions}
|
notificationOptions={notificationOptions}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
|
|||||||
@@ -1,28 +1,19 @@
|
|||||||
import { UptimeForm } from "./UptimeForm";
|
import { UptimeForm } from "./UptimeForm";
|
||||||
|
|
||||||
import humanInterval from "human-interval";
|
|
||||||
import { z } from "zod";
|
|
||||||
import { monitorSchema } from "@/validation/zod";
|
|
||||||
import { useGet, usePost } from "@/hooks/UseApi";
|
import { useGet, usePost } from "@/hooks/UseApi";
|
||||||
import type { ApiResponse } from "@/types/api";
|
import type { ApiResponse } from "@/types/api";
|
||||||
import { useNavigate } from "react-router";
|
import { useNavigate } from "react-router";
|
||||||
import type { INotificationChannel } from "@/types/notification-channel";
|
import type { INotificationChannel } from "@/types/notification-channel";
|
||||||
|
import type { SubmitValues } from "@/pages/uptime/UptimeForm";
|
||||||
const UptimeCreatePage = () => {
|
const UptimeCreatePage = () => {
|
||||||
type FormValues = z.infer<typeof monitorSchema>;
|
|
||||||
type SubmitValues = Omit<FormValues, "interval"> & {
|
|
||||||
interval: number | undefined;
|
|
||||||
};
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
|
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
|
||||||
"/notification-channels"
|
"/notification-channels"
|
||||||
);
|
);
|
||||||
const { post, loading, error } = usePost<SubmitValues>();
|
const { post, loading, error } = usePost<SubmitValues>();
|
||||||
|
|
||||||
const onSubmit = async (data: FormValues) => {
|
const onSubmit = async (data: SubmitValues) => {
|
||||||
let interval = humanInterval(data.interval);
|
const result = await post("/monitors", data);
|
||||||
if (!interval) interval = 60000;
|
|
||||||
const submitData = { ...data, interval };
|
|
||||||
const result = await post("/monitors", submitData);
|
|
||||||
if (result) {
|
if (result) {
|
||||||
navigate("/uptime");
|
navigate("/uptime");
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { Typography } from "@mui/material";
|
|||||||
|
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { monitorSchema } from "@/validation/zod";
|
import { monitorSchema } from "@/validation";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import {
|
import {
|
||||||
@@ -23,10 +23,14 @@ import {
|
|||||||
useWatch,
|
useWatch,
|
||||||
type SubmitHandler,
|
type SubmitHandler,
|
||||||
} from "react-hook-form";
|
} from "react-hook-form";
|
||||||
|
import type { IMonitor } from "@/types/monitor";
|
||||||
import { useTheme } from "@mui/material/styles";
|
import { useTheme } from "@mui/material/styles";
|
||||||
import { useInitForm } from "@/hooks/forms/UseInitMonitorFrom";
|
import { useInitForm } from "@/hooks/forms/UseInitMonitorFrom";
|
||||||
|
|
||||||
type FormValues = z.infer<typeof monitorSchema>;
|
export type FormValues = z.infer<typeof monitorSchema>;
|
||||||
|
export type SubmitValues = Omit<z.infer<typeof monitorSchema>, "interval"> & {
|
||||||
|
interval: number | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
export const UptimeForm = ({
|
export const UptimeForm = ({
|
||||||
mode = "create",
|
mode = "create",
|
||||||
@@ -36,14 +40,14 @@ export const UptimeForm = ({
|
|||||||
loading,
|
loading,
|
||||||
}: {
|
}: {
|
||||||
mode?: "create" | "configure";
|
mode?: "create" | "configure";
|
||||||
initialData?: Partial<FormValues>;
|
initialData?: IMonitor;
|
||||||
onSubmit: SubmitHandler<FormValues>;
|
onSubmit: SubmitHandler<SubmitValues>;
|
||||||
notificationOptions: any[];
|
notificationOptions: any[];
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { defaults } = useInitForm({ initialData: initialData });
|
const { defaults, formToApi } = useInitForm({ initialData: initialData });
|
||||||
const urlInputRef = useRef<HTMLInputElement>(null);
|
const urlInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@@ -73,6 +77,10 @@ export const UptimeForm = ({
|
|||||||
name: "notificationChannels",
|
name: "notificationChannels",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const submitForm = (formData: FormValues) => {
|
||||||
|
onSubmit(formToApi(formData));
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selectedType) return;
|
if (!selectedType) return;
|
||||||
|
|
||||||
@@ -108,7 +116,7 @@ export const UptimeForm = ({
|
|||||||
}, [selectedType]);
|
}, [selectedType]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
|
<BasePage component={"form"} onSubmit={handleSubmit(submitForm)}>
|
||||||
{mode === "create" && (
|
{mode === "create" && (
|
||||||
<ConfigBox
|
<ConfigBox
|
||||||
title={t("monitors.uptime.form.type.title")}
|
title={t("monitors.uptime.form.type.title")}
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ export interface IMonitor {
|
|||||||
latestChecks: ICheck[];
|
latestChecks: ICheck[];
|
||||||
n: number;
|
n: number;
|
||||||
name: string;
|
name: string;
|
||||||
|
port: number;
|
||||||
notificationChannels: string[];
|
notificationChannels: string[];
|
||||||
status: MonitorStatus;
|
status: MonitorStatus;
|
||||||
type: string;
|
type: string;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
export * from "./zod";
|
export * from "./zod";
|
||||||
export * from "./login";
|
export * from "./login";
|
||||||
export * from "./register";
|
export * from "./register";
|
||||||
|
export * from "./monitor";
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import humanInterval from "human-interval";
|
||||||
|
const urlRegex =
|
||||||
|
/^(https?:\/\/)?(localhost|([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|[a-zA-Z0-9-]+|(\d{1,3}\.){3}\d{1,3})(:\d{1,5})?(\/.*)?$/;
|
||||||
|
|
||||||
|
const durationSchema = z.string().superRefine((val, ctx) => {
|
||||||
|
// if (!val || val.trim() === "") return;
|
||||||
|
const ms = humanInterval(val);
|
||||||
|
|
||||||
|
if (!ms || isNaN(ms)) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
message: "Invalid duration format",
|
||||||
|
});
|
||||||
|
} else if (ms < 10000) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
message: "Minimum duration is 10 seconds",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const monitorSchema = z
|
||||||
|
.object({
|
||||||
|
type: z.string().min(1, "You must select an option"),
|
||||||
|
url: z.string().min(1, "URL is required").regex(urlRegex, "Invalid URL"),
|
||||||
|
n: z.coerce
|
||||||
|
.number({ message: "Number required" })
|
||||||
|
.min(1, "Minimum value is 1")
|
||||||
|
.max(25, "Maximum value is 25"),
|
||||||
|
port: z.coerce.number().optional(),
|
||||||
|
notificationChannels: z.array(z.string()).optional().default([]),
|
||||||
|
name: z.string().min(1, "Display name is required"),
|
||||||
|
interval: durationSchema,
|
||||||
|
rejectUnauthorized: z.boolean().default(true),
|
||||||
|
})
|
||||||
|
.superRefine((data, ctx) => {
|
||||||
|
if (data.type === "port") {
|
||||||
|
if (!data.port) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
message: "Port is required for port monitoring",
|
||||||
|
path: ["port"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (isNaN(Number(data.port))) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
message: "Port must be a number",
|
||||||
|
path: ["port"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (Number(data.port) < 1 || Number(data.port) > 65535) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
message: "Port must be between 1 and 65535",
|
||||||
|
path: ["port"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -71,51 +71,7 @@ const optionalString = <T extends z.ZodTypeAny>(schema: T) =>
|
|||||||
schema.optional()
|
schema.optional()
|
||||||
);
|
);
|
||||||
|
|
||||||
export const monitorSchema = z
|
// moved to client/src/validation/monitor.ts
|
||||||
.object({
|
|
||||||
type: z.string().min(1, "You must select an option"),
|
|
||||||
url: z.string().min(1, "URL is required").regex(urlRegex, "Invalid URL"),
|
|
||||||
n: z.coerce
|
|
||||||
.number({ message: "Number required" })
|
|
||||||
.min(1, "Minimum value is 1")
|
|
||||||
.max(25, "Maximum value is 25"),
|
|
||||||
port: z.coerce.number().optional(),
|
|
||||||
notificationChannels: z.array(z.string()).optional().default([]),
|
|
||||||
name: z.string().min(1, "Display name is required"),
|
|
||||||
interval: durationSchema,
|
|
||||||
rejectUnauthorized: z.boolean().default(true),
|
|
||||||
})
|
|
||||||
.superRefine((data, ctx) => {
|
|
||||||
if (data.type === "port") {
|
|
||||||
if (!data.port) {
|
|
||||||
ctx.addIssue({
|
|
||||||
code: "custom",
|
|
||||||
message: "Port is required for port monitoring",
|
|
||||||
path: ["port"],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (isNaN(Number(data.port))) {
|
|
||||||
ctx.addIssue({
|
|
||||||
code: "custom",
|
|
||||||
message: "Port must be a number",
|
|
||||||
path: ["port"],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (Number(data.port) < 1 || Number(data.port) > 65535) {
|
|
||||||
ctx.addIssue({
|
|
||||||
code: "custom",
|
|
||||||
message: "Port must be between 1 and 65535",
|
|
||||||
path: ["port"],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.transform((data) => {
|
|
||||||
if (data.type !== "port") {
|
|
||||||
return { ...data, port: undefined };
|
|
||||||
}
|
|
||||||
return data;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const monitorSchemaPageSpeed = z.object({
|
export const monitorSchemaPageSpeed = z.object({
|
||||||
type: z.string().min(1, "You must select an option"),
|
type: z.string().min(1, "You must select an option"),
|
||||||
|
|||||||
Reference in new issue
Block a user