put/create
This commit is contained in:
1 parent
f538f61464
commit
67da6c61cf
9 files changed
+210
-100
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import useSWR from "swr";
|
||||
import type { SWRConfiguration } from "swr";
|
||||
import type { AxiosRequestConfig } from "axios";
|
||||
import { get, patch, post, deleteOp } from "@/Utils/ApiClient";
|
||||
import { get, patch, post, put, deleteOp } from "@/Utils/ApiClient";
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/Hooks/UseToast";
|
||||
|
||||
@@ -109,6 +109,42 @@ export const usePatch = <B = any, R = any>() => {
|
||||
return { patch: patchFn, loading, error };
|
||||
};
|
||||
|
||||
export const usePut = <B = any, R = any>() => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { toastError, toastSuccess } = useToast();
|
||||
|
||||
const putFn = async (
|
||||
endpoint: string,
|
||||
body?: B,
|
||||
config?: AxiosRequestConfig
|
||||
): Promise<ApiResponse<R> | null> => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await put<ApiResponse<R>>(endpoint, body, {
|
||||
...config,
|
||||
headers: {
|
||||
...config?.headers,
|
||||
},
|
||||
});
|
||||
toastSuccess(res.data?.msg || "Operation successful");
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
const errMsg = err?.response?.data?.msg || err.message || "An error occurred";
|
||||
toastError(errMsg);
|
||||
setError(errMsg);
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { put: putFn, loading, error };
|
||||
};
|
||||
|
||||
export const useDelete = <R = any>() => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -9,6 +9,7 @@ interface UseMonitorFormOptions {
|
||||
|
||||
const getBaseDefaults = (data?: Monitor | null) => ({
|
||||
name: data?.name || "",
|
||||
description: data?.description || "",
|
||||
interval: data?.interval || 60000,
|
||||
notifications: data?.notifications || [],
|
||||
statusWindowSize: data?.statusWindowSize || 5,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from "react";
|
||||
import { useEffect } from "react";
|
||||
import { useParams } from "react-router";
|
||||
import { useParams, useLocation, useNavigate } from "react-router";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useTheme } from "@mui/material";
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
SwitchComponent as Switch,
|
||||
SliderWithLabel,
|
||||
} from "@/Components/v2/inputs";
|
||||
import { useGet } from "@/Hooks/UseApi";
|
||||
import { useGet, usePost, usePut } from "@/Hooks/UseApi";
|
||||
import { useMonitorForm } from "@/Hooks/useMonitorForm";
|
||||
import type { Monitor, MonitorType } from "@/Types/Monitor";
|
||||
import type { Notification } from "@/Types/Notification";
|
||||
@@ -116,8 +116,22 @@ const CreateMonitorPage = () => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const { monitorId } = useParams();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const isEditMode = Boolean(monitorId);
|
||||
|
||||
// Extract page type from URL path (e.g., /pagespeed/create -> pagespeed)
|
||||
const pageType = useMemo(() => {
|
||||
const pathSegments = location.pathname.split("/").filter(Boolean);
|
||||
const firstSegment = pathSegments[0];
|
||||
if (firstSegment === "pagespeed") return "pagespeed";
|
||||
if (firstSegment === "infrastructure") return "hardware";
|
||||
return "uptime";
|
||||
}, [location.pathname]);
|
||||
|
||||
const showTypeSelector = pageType === "uptime" && !isEditMode;
|
||||
const defaultType: MonitorType = pageType === "pagespeed" ? "pagespeed" : pageType === "hardware" ? "hardware" : "http";
|
||||
|
||||
const { data: existingMonitor } = useGet<Monitor>(
|
||||
isEditMode ? `/monitors/${monitorId}` : null
|
||||
);
|
||||
@@ -125,7 +139,7 @@ const CreateMonitorPage = () => {
|
||||
// Fetch notifications for the team
|
||||
const { data: notifications } = useGet<Notification[]>("/notifications/team");
|
||||
|
||||
const { schema, defaults } = useMonitorForm({ data: existingMonitor ?? null });
|
||||
const { schema, defaults } = useMonitorForm({ data: existingMonitor ?? null, defaultType });
|
||||
|
||||
const form = useForm<MonitorFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
@@ -148,8 +162,28 @@ const CreateMonitorPage = () => {
|
||||
[watchedType, t]
|
||||
);
|
||||
|
||||
const { post, loading: isCreating } = usePost<MonitorFormData, Monitor>();
|
||||
const { put, loading: isUpdating } = usePut<MonitorFormData, Monitor>();
|
||||
const isSubmitting = isCreating || isUpdating;
|
||||
|
||||
const onSubmit = async (data: MonitorFormData) => {
|
||||
console.log(data);
|
||||
let result;
|
||||
if (isEditMode && monitorId) {
|
||||
result = await put(`/monitors/${monitorId}`, data);
|
||||
} else {
|
||||
result = await post("/monitors", data);
|
||||
}
|
||||
|
||||
if (result?.success) {
|
||||
// Navigate based on page type
|
||||
if (pageType === "pagespeed") {
|
||||
navigate("/pagespeed");
|
||||
} else if (pageType === "hardware") {
|
||||
navigate("/infrastructure");
|
||||
} else {
|
||||
navigate("/uptime");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const onError = (errors: unknown) => {
|
||||
@@ -161,67 +195,55 @@ const CreateMonitorPage = () => {
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit, onError)}
|
||||
>
|
||||
{/* Monitor Type Selection */}
|
||||
<ConfigBox
|
||||
title={t("pages.createMonitor.form.type.title")}
|
||||
subtitle={t("pages.createMonitor.form.type.description")}
|
||||
rightContent={
|
||||
<Controller
|
||||
name="type"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<FormControl error={!!fieldState.error}>
|
||||
<RadioGroup
|
||||
{...field}
|
||||
sx={{ gap: theme.spacing(6) }}
|
||||
>
|
||||
<RadioWithDescription
|
||||
value="http"
|
||||
label={t("pages.createMonitor.form.type.optionHttp")}
|
||||
description={t("pages.createMonitor.form.type.optionHttpDescription")}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="ping"
|
||||
label={t("pages.createMonitor.form.type.optionPing")}
|
||||
description={t("pages.createMonitor.form.type.optionPingDescription")}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="docker"
|
||||
label={t("pages.createMonitor.form.type.optionDocker")}
|
||||
description={t(
|
||||
"pages.createMonitor.form.type.optionDockerDescription"
|
||||
)}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="port"
|
||||
label={t("pages.createMonitor.form.type.optionPort")}
|
||||
description={t("pages.createMonitor.form.type.optionPortDescription")}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="game"
|
||||
label={t("pages.createMonitor.form.type.optionGame")}
|
||||
description={t("pages.createMonitor.form.type.optionGameDescription")}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="pagespeed"
|
||||
label={t("pages.createMonitor.form.type.optionPagespeed")}
|
||||
description={t(
|
||||
"pages.createMonitor.form.type.optionPagespeedDescription"
|
||||
)}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="hardware"
|
||||
label={t("pages.createMonitor.form.type.optionHardware")}
|
||||
description={t(
|
||||
"pages.createMonitor.form.type.optionHardwareDescription"
|
||||
)}
|
||||
/>
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{/* Monitor Type Selection - only shown for uptime monitors */}
|
||||
{showTypeSelector && (
|
||||
<ConfigBox
|
||||
title={t("pages.createMonitor.form.type.title")}
|
||||
subtitle={t("pages.createMonitor.form.type.description")}
|
||||
rightContent={
|
||||
<Controller
|
||||
name="type"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<FormControl error={!!fieldState.error}>
|
||||
<RadioGroup
|
||||
{...field}
|
||||
sx={{ gap: theme.spacing(6) }}
|
||||
>
|
||||
<RadioWithDescription
|
||||
value="http"
|
||||
label={t("pages.createMonitor.form.type.optionHttp")}
|
||||
description={t("pages.createMonitor.form.type.optionHttpDescription")}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="ping"
|
||||
label={t("pages.createMonitor.form.type.optionPing")}
|
||||
description={t("pages.createMonitor.form.type.optionPingDescription")}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="docker"
|
||||
label={t("pages.createMonitor.form.type.optionDocker")}
|
||||
description={t(
|
||||
"pages.createMonitor.form.type.optionDockerDescription"
|
||||
)}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="port"
|
||||
label={t("pages.createMonitor.form.type.optionPort")}
|
||||
description={t("pages.createMonitor.form.type.optionPortDescription")}
|
||||
/>
|
||||
<RadioWithDescription
|
||||
value="game"
|
||||
label={t("pages.createMonitor.form.type.optionGame")}
|
||||
description={t("pages.createMonitor.form.type.optionGameDescription")}
|
||||
/>
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* General Settings - Dynamic based on type */}
|
||||
<ConfigBox
|
||||
@@ -241,6 +263,7 @@ const CreateMonitorPage = () => {
|
||||
fieldLabel={generalSettingsConfig.urlLabel}
|
||||
placeholder={generalSettingsConfig.urlPlaceholder}
|
||||
fullWidth
|
||||
disabled={isEditMode}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
@@ -506,7 +529,7 @@ const CreateMonitorPage = () => {
|
||||
justifyContent="flex-end"
|
||||
>
|
||||
<Button
|
||||
loading={false}
|
||||
loading={isSubmitting}
|
||||
type="submit"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
|
||||
+42
-16
@@ -80,16 +80,6 @@ const Routes = () => {
|
||||
path="/"
|
||||
element={<Navigate to="/uptime" />}
|
||||
/>
|
||||
<Route
|
||||
path="/testing"
|
||||
element={
|
||||
<>
|
||||
<ThemeProvider theme={v2theme}>
|
||||
<CreateMonitor />
|
||||
</ThemeProvider>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/uptime"
|
||||
element={
|
||||
@@ -108,7 +98,13 @@ const Routes = () => {
|
||||
|
||||
<Route
|
||||
path="/uptime/create"
|
||||
element={<UptimeCreate />}
|
||||
element={
|
||||
<>
|
||||
<ThemeProvider theme={v2theme}>
|
||||
<CreateMonitor />
|
||||
</ThemeProvider>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/uptime/create/:monitorId"
|
||||
@@ -126,7 +122,13 @@ const Routes = () => {
|
||||
/>
|
||||
<Route
|
||||
path="/uptime/configure/:monitorId/"
|
||||
element={<UptimeCreate />}
|
||||
element={
|
||||
<>
|
||||
<ThemeProvider theme={v2theme}>
|
||||
<CreateMonitor />
|
||||
</ThemeProvider>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
@@ -141,7 +143,13 @@ const Routes = () => {
|
||||
/>
|
||||
<Route
|
||||
path="pagespeed/create"
|
||||
element={<PageSpeedCreate />}
|
||||
element={
|
||||
<>
|
||||
<ThemeProvider theme={v2theme}>
|
||||
<CreateMonitor />
|
||||
</ThemeProvider>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="pagespeed/:monitorId"
|
||||
@@ -155,7 +163,13 @@ const Routes = () => {
|
||||
/>
|
||||
<Route
|
||||
path="pagespeed/configure/:monitorId"
|
||||
element={<PageSpeedCreate />}
|
||||
element={
|
||||
<>
|
||||
<ThemeProvider theme={v2theme}>
|
||||
<CreateMonitor />
|
||||
</ThemeProvider>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="infrastructure"
|
||||
@@ -169,11 +183,23 @@ const Routes = () => {
|
||||
/>
|
||||
<Route
|
||||
path="infrastructure/create"
|
||||
element={<InfrastructureCreate />}
|
||||
element={
|
||||
<>
|
||||
<ThemeProvider theme={v2theme}>
|
||||
<CreateMonitor />
|
||||
</ThemeProvider>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/infrastructure/configure/:monitorId"
|
||||
element={<InfrastructureCreate />}
|
||||
element={
|
||||
<>
|
||||
<ThemeProvider theme={v2theme}>
|
||||
<CreateMonitor />
|
||||
</ThemeProvider>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="infrastructure/:monitorId"
|
||||
|
||||
@@ -67,6 +67,12 @@ export const patch = <T>(
|
||||
config: AxiosRequestConfig = {}
|
||||
): Promise<AxiosResponse<T>> => api.patch<T>(url, data, config);
|
||||
|
||||
export const put = <T>(
|
||||
url: string,
|
||||
data: unknown,
|
||||
config: AxiosRequestConfig = {}
|
||||
): Promise<AxiosResponse<T>> => api.put<T>(url, data, config);
|
||||
|
||||
export const deleteOp = <T>(
|
||||
url: string,
|
||||
config: AxiosRequestConfig = {}
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// URL schema with custom error message
|
||||
const urlSchema = z.url({ message: "Please enter a valid URL" });
|
||||
|
||||
// Common base schema for all monitor types
|
||||
const baseSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.min(1, "Monitor name is required")
|
||||
.max(50, "Monitor name must be at most 50 characters"),
|
||||
description: z.string().optional(),
|
||||
interval: z.number().min(15000, "Interval must be at least 15 seconds"),
|
||||
notifications: z.array(z.string()),
|
||||
statusWindowSize: z
|
||||
@@ -21,10 +25,7 @@ const baseSchema = z.object({
|
||||
// HTTP monitor schema
|
||||
const httpSchema = baseSchema.extend({
|
||||
type: z.literal("http"),
|
||||
url: z
|
||||
.string()
|
||||
.min(1, "URL is required")
|
||||
.url("Please enter a valid URL"),
|
||||
url: urlSchema,
|
||||
ignoreTlsErrors: z.boolean(),
|
||||
matchMethod: z.enum(["equal", "include", "regex", ""]).optional(),
|
||||
expectedValue: z.string().optional(),
|
||||
@@ -67,16 +68,13 @@ const gameSchema = baseSchema.extend({
|
||||
// PageSpeed monitor schema
|
||||
const pagespeedSchema = baseSchema.extend({
|
||||
type: z.literal("pagespeed"),
|
||||
url: z
|
||||
.string()
|
||||
.min(1, "URL is required")
|
||||
.url("Please enter a valid URL"),
|
||||
url: urlSchema,
|
||||
});
|
||||
|
||||
// Hardware/Infrastructure monitor schema
|
||||
const hardwareSchema = baseSchema.extend({
|
||||
type: z.literal("hardware"),
|
||||
url: z.string({ message: "URL is required" }).min(1, "URL is required"),
|
||||
url: urlSchema,
|
||||
secret: z.string({ message: "Secret is required" }).min(1, "Secret is required"),
|
||||
cpuAlertThreshold: z
|
||||
.number()
|
||||
|
||||
@@ -353,6 +353,15 @@
|
||||
}
|
||||
},
|
||||
"pageSpeed": {
|
||||
"fallback": {
|
||||
"actionButton": "Create a monitor!",
|
||||
"checks": [
|
||||
"Report on the user experience of a page",
|
||||
"Help analyze webpage speed",
|
||||
"Give suggestions on how the page can be improved"
|
||||
],
|
||||
"title": "A PageSpeed monitor is used to:"
|
||||
},
|
||||
"table": {
|
||||
"headers": {
|
||||
"pageSpeedScore": "PageSpeed score"
|
||||
@@ -376,6 +385,15 @@
|
||||
}
|
||||
},
|
||||
"infrastructure": {
|
||||
"fallback": {
|
||||
"actionButton": "Create a monitor!",
|
||||
"checks": [
|
||||
"Track the performance of your servers",
|
||||
"Identify bottlenecks and optimize usage",
|
||||
"Ensure reliability with real-time monitoring"
|
||||
],
|
||||
"title": "An infrastructure monitor is used to:"
|
||||
},
|
||||
"table": {
|
||||
"headers": {
|
||||
"cpu": "CPU",
|
||||
|
||||
+5
-3
@@ -28,18 +28,20 @@ export const createApp = ({
|
||||
}) => {
|
||||
const allowedOrigin = envSettings.clientHost;
|
||||
const app = express();
|
||||
|
||||
app.use(generalApiLimiter);
|
||||
// Static files
|
||||
app.use(express.static(frontendPath));
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin: allowedOrigin,
|
||||
methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
|
||||
allowedHeaders: ["Content-Type", "Authorization"],
|
||||
allowedHeaders: ["Content-Type", "Authorization", "Accept-Language"],
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
|
||||
app.use(express.static(frontendPath));
|
||||
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
|
||||
|
||||
@@ -152,7 +152,7 @@ const getCertificateParamValidation = joi.object({
|
||||
const createMonitorBodyValidation = joi.object({
|
||||
_id: joi.string(),
|
||||
name: joi.string().required(),
|
||||
description: joi.string().required(),
|
||||
description: joi.string().allow(null, ""),
|
||||
type: joi.string().required(),
|
||||
statusWindowSize: joi.number().min(1).max(20).default(5),
|
||||
statusWindowThreshold: joi.number().min(1).max(100).default(60),
|
||||
@@ -171,7 +171,7 @@ const createMonitorBodyValidation = joi.object({
|
||||
secret: joi.string(),
|
||||
jsonPath: joi.string().allow(""),
|
||||
expectedValue: joi.string().allow(""),
|
||||
matchMethod: joi.string(),
|
||||
matchMethod: joi.string().allow(null, ""),
|
||||
gameId: joi.string().allow(""),
|
||||
selectedDisks: joi.array().items(joi.string()).optional(),
|
||||
group: joi.string().max(50).trim().allow(null, "").optional(),
|
||||
@@ -188,7 +188,7 @@ const editMonitorBodyValidation = joi.object({
|
||||
name: joi.string(),
|
||||
statusWindowSize: joi.number().min(1).max(20).default(5),
|
||||
statusWindowThreshold: joi.number().min(1).max(100).default(60),
|
||||
description: joi.string(),
|
||||
description: joi.string().allow(null, ""),
|
||||
interval: joi.number(),
|
||||
notifications: joi.array().items(joi.string()),
|
||||
secret: joi.string(),
|
||||
@@ -203,10 +203,10 @@ const editMonitorBodyValidation = joi.object({
|
||||
usage_disk: joi.number(),
|
||||
usage_temperature: joi.number(),
|
||||
}),
|
||||
gameId: joi.string(),
|
||||
gameId: joi.string().allow(""),
|
||||
selectedDisks: joi.array().items(joi.string()).optional(),
|
||||
group: joi.string().max(50).trim().allow(null, "").optional(),
|
||||
});
|
||||
}).options({ stripUnknown: true });
|
||||
|
||||
const pauseMonitorParamValidation = joi.object({
|
||||
monitorId: joi.string().required(),
|
||||
|
||||
Reference in new issue
Block a user